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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With