仅匹配正则表达式中字符的首次出现

时间:2020-02-06 10:25:14

标签: java regex

您好,我想匹配所有字符串,例如:{ anything character },但是我想在String的末尾排除双{{ at first or }}。我尝试使用类似^\\{.*\\}$的模式来执行此操作,但是此模式匹配{{ anything character }}{ anything character }},并且我不想匹配它。

1 个答案:

答案 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");