匹配右括号时Android中的正则表达式模式错误 [英] Regex pattern error in Android when matching closing brace
问题描述
我正在使用java.util.regex.Pattern类来匹配Android程序中的字符串.
I am using java.util.regex.Pattern class to match a string in a Android program.
if(Pattern.matches("\\{\\{.*?}}", element.getValue())) {
...
} else {
...
}
然后出现以下错误.
Caused by: java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 8
\{\{.*?}}
我正在使用Android Studio和Open JDK.为了测试正则表达式,我在Netbeans中编写了一个简单的程序,它运行良好. Netbeans也使用openjdk.
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}}"));
为什么正则表达式在android项目中给出错误?
Why the regular expression is giving an error in android project?
推荐答案
使用
"\\{\\{.*?\\}\\}"
问题在于,Android中使用的正则表达式引擎是 ICU引擎,即与Java不同,表示文字打开/关闭花括号的 和都必须在ICU正则表达式模式中转义.
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.
在绝大多数的正则表达式中,不必逃避}
,但是ICU regex引擎不是这种情况,它不能基于模式上下文来推断}
的含义.例如. PCRE,.NET,Python,Java正则表达式以[a-z]}
模式找到}
,并且由于之前没有{
,因此他们知道"它不是
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.
这篇关于匹配右括号时Android中的正则表达式模式错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!