Java regular expression to match {{characters inside double curly brace}}

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 }}!).

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.


You have to use non-greedy match:

\{\{.*?\}\}

to match everything between braces, use:

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

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

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

Wikipedia explains it pretty well.

Tags:

Java

Regex