5

I am using java.util.regex.Pattern class to match a string in a Android program.

if(Pattern.matches("\\{\\{.*?}}", element.getValue())) {
   ...             
} else {
   ...
}

And I got the following error.

 Caused by: java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 8
                                                                  \{\{.*?}}

I am using Android studio and Open JDK. To test the regex expression I wrote a simple program in Netbeans and it works fine. Netbeans also use openjdk.

System.out.println(Pattern.matches("\\{\\{.*?}}", "{{hello:sdf}}"));

Why the regular expression is giving an error in android project?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
chamathabeysinghe
  • 858
  • 2
  • 13
  • 34
  • 2
    I think you just need to use `if (element.getValue().matches("\\{\\{.*?}}"))`, try also escaping `}`s if you still have issues. – Wiktor Stribiżew Jul 13 '17 at 08:06
  • I have noticed on pre api version 21 `java.util.regex` matcher does not work correctly. It is better to rather use `com.google.code.regexp` – archLucifer Jul 13 '17 at 08:54

1 Answers1

11

Use

"\\{\\{.*?\\}\\}"

The issue is that the regex engine used in Android is an ICU engine that is different from Java one, and both { and } that represent literal open/close curly braces must be escaped in ICU regex patterns.

In the overwhelming majority of regex flavors } does not have to be escaped, but it is not the case with the ICU regex engine that cannot deduce the } meaning based on the pattern context. E.g. PCRE, .NET, Python, Java regexes find } in [a-z]} pattern and as there is no { before, they "know" it is not a part of the limiting quantifier construct. ICU is not that smart. It still thinks there must be a { that is followed with digit(s) before } and reports an error if it is unescaped.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563