如何在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();
}
答案 0 :(得分:12)
问题实际上是因为backtracking。你的正则表达式:
"\\b(fruit)\\s+([^a]+\\w+)\\b"
说“水果,后跟一个或多个空格,后跟一个或多个非'a'字符,后跟一个或多个'字'字符”。这有两个空格失败的原因是因为\s+
匹配第一个空格,但是然后返回第二个,然后满足[^a]+
(第二个空格)和\s+
部分(第一部分)。
我认为你可以通过简单地使用posessive量词来修复它,这将是\s++
。这告诉\s
而不是返回第二个空格字符。您可以找到有关Java量词here的文档。
作为一个例子,以下是Rubular的两个例子:
\s
(根据您的描述给出预期结果)[^a\]+
and \w+
。请注意,第二个匹配组(表示[^a]+
)正在捕获第二个空格字符。