如何在Java正则表达式中匹配多个空格字符?
我有一个正在尝试匹配的正则表达式.当我有两个或更多空格字符时,正则表达式失败.
public static void main(String[] args) {
String pattern = "\\b(fruit)\\s+([^a]+\\w+)\\b"; //Match 'fruit' not followed by a word that begins with 'a'
String str = "fruit apple"; //One space character will not be matched
String str_fail = "fruit apple"; //Two space characters will be matched
System.out.println(preg_match(pattern,str)); //False (Thats what I want)
System.out.println(preg_match(pattern,str_fail)); //True (Regex fail)
}
public static boolean preg_match(String pattern,String subject) {
Pattern regex = Pattern.compile(pattern);
Matcher regexMatcher = regex.matcher(subject);
return regexMatcher.find();
}
Run Code Online (Sandbox Code Playgroud)
eld*_*his 12
问题实际上是因为回溯.你的正则表达式:
"\\b(fruit)\\s+([^a]+\\w+)\\b"
Run Code Online (Sandbox Code Playgroud)
说"水果,后跟一个或多个空格,后跟一个或多个非'a'字符,后跟一个或多个'字'字符".这与两个空格失败的原因是因为\s+匹配第一个空格,但随后返回第二[^a]+个空格,然后满足(第二个空格)和\s+部分(第一个空格).
我认为你可以通过简单地使用posessive量词来修复它,这将是\s++.这告诉\s 不要回馈第二个空格字符.您可以在此处找到有关Java量词的文档.
作为一个例子,这里有两个Rubular的例子:
\s(给出预期结果,来自你描述的)[^a\]+和\w+.请注意,第二个匹配组(表示[^a]+)正在捕获第二个空格字符.| 归档时间: |
|
| 查看次数: |
36378 次 |
| 最近记录: |