6

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?

2
  • 2
    I think you just need to use if (element.getValue().matches("\\{\\{.*?}}")), try also escaping }s if you still have issues. Commented Jul 13, 2017 at 8: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 Commented Jul 13, 2017 at 8:54

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.