Java正则表达式匹配双花括号}中的{{字符}

时间:2022-03-14 12:13:00

I am trying to match everything inside double curly brackets in a string. I am using the following expression:

我正在尝试匹配字符串中双花括号内的所有内容。我正在使用以下表达式:

\{\{.*\}\}

Some examples:

一些例子:

The {{dog}} is not a cat. This correctly matches {{dog}}

{狗}不是猫。这个正确匹配{ {狗} }

However,
The {{dog}} is a {{cat}} matches everything after the first match instead of returning two matches. I want it to match twice, once for {{dog}} and once for {{cat}}

但是,{dog}是{cat}在第一次比赛之后匹配所有的东西,而不是返回两个比赛。我希望它匹配两次,一次为{{dog},一次为{cat}

Does anyone know how to do this?

有人知道怎么做吗?

Thanks.

谢谢。

4 个解决方案

#1


8  

The greedy .* matches anything (except line breaks), so when there are more than one }} in the string, it always matches the last }} (if there aren't any \r and \n between the two }}!).

这个贪心的。*匹配任何东西(除了换行符),所以当字符串中有多个}时,它总是匹配最后的}(如果两个}之间没有任何\r和\n !)

Try to make the .* match reluctant (ungreedy) like this:

试着使。*匹配不情愿(不贪婪)像这样:

\{\{.*?}}

That's correct, you needn't escape the }.

这是正确的,你不必逃避。

You could also do:

你也可以做的事:

\{\{[^}]*}}

if a {{ ... }} cannot contain a single } itself.

如果一个{ {…}不能包含单个}本身。

#2


5  

Try with \{\{.*?\}\}

试着用\ { \ {。* ? \ } \ }

I believe it's because the pattern you have is greedy.

我相信这是因为你的模式是贪婪的。

Wikipedia explains it pretty well.

*解释得很好。

#3


1  

You have to use non-greedy match:

你必须使用非贪婪匹配:

\{\{.*?\}\}

to match everything between braces, use:

要匹配大括号之间的所有内容,请使用:

\{\{(.*?)\}\}

#4


0  

What you need is the "non-greedy" modifier - so your regex is \{\{.+?\}\}

您需要的是“非贪婪”修改器——因此您的regex是\{{{{.+?\}}

#1


8  

The greedy .* matches anything (except line breaks), so when there are more than one }} in the string, it always matches the last }} (if there aren't any \r and \n between the two }}!).

这个贪心的。*匹配任何东西(除了换行符),所以当字符串中有多个}时,它总是匹配最后的}(如果两个}之间没有任何\r和\n !)

Try to make the .* match reluctant (ungreedy) like this:

试着使。*匹配不情愿(不贪婪)像这样:

\{\{.*?}}

That's correct, you needn't escape the }.

这是正确的,你不必逃避。

You could also do:

你也可以做的事:

\{\{[^}]*}}

if a {{ ... }} cannot contain a single } itself.

如果一个{ {…}不能包含单个}本身。

#2


5  

Try with \{\{.*?\}\}

试着用\ { \ {。* ? \ } \ }

I believe it's because the pattern you have is greedy.

我相信这是因为你的模式是贪婪的。

Wikipedia explains it pretty well.

*解释得很好。

#3


1  

You have to use non-greedy match:

你必须使用非贪婪匹配:

\{\{.*?\}\}

to match everything between braces, use:

要匹配大括号之间的所有内容,请使用:

\{\{(.*?)\}\}

#4


0  

What you need is the "non-greedy" modifier - so your regex is \{\{.+?\}\}

您需要的是“非贪婪”修改器——因此您的regex是\{{{{.+?\}}