您好,我想匹配所有字符串,例如:{ anything character }
,但是我想在String的末尾排除双{{ at first or }}
。我尝试使用类似^\\{.*\\}$
的模式来执行此操作,但是此模式匹配{{ anything character }}
或{ anything character }}
,并且我不想匹配它。
答案 0 :(得分:1)
您可以使用否定的字符类排除一个或多个字符,例如[^{]
或[^}]
或[^{}]
。因此,一种方法是:
/^\{[^{}]*\}$/
实时示例:
const rex = /^\{[^{}]*\}$/;
console.log(rex.test("{matches}") ? "matches" : "doesn't match");
console.log(rex.test("{{doesn't match}}") ? "matches" : "doesn't match");
如果您只想禁止第一个{
之后的{
和结尾}
之前的}
,则可以使用否定的超前查询:
/^\{(?!{).*\}(?!})$/
(?!{)
的意思是“这里没有{
”,但不消耗任何东西。
实时示例:
const rex = /^\{(?!{).*\}(?!})$/;
console.log(rex.test("{matc{h}es}") ? "matches" : "doesn't match");
console.log(rex.test("{{doesn't match}}") ? "matches" : "doesn't match");