Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex pattern error in Android when matching closing brace

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?

like image 924
chamathabeysinghe Avatar asked Jul 13 '17 08:07

chamathabeysinghe


1 Answers

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.

like image 104
Wiktor Stribiżew Avatar answered Nov 06 '22 08:11

Wiktor Stribiżew