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

Viewed 6418

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}}

Does anyone know how to do this?

Thanks.

5 Answers

Try this, it worked for me:

Pattern pattern = Pattern.compile("\\{\\{(.*?)\\}\\}");
Matcher matchPattern = pattern.matcher("The {{cat}} loves the {{dog}}");
while(matchPattern.find()) {
    System.out.println(matchPattern.group(1));
}
Related