Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...