Java Regex:如何匹配一个或多个空格字符

如何在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(); } 

问题实际上是因为回溯 。 你的正则表达式:

  "\\b(fruit)\\s+([^a]+\\w+)\\b" 

说“水果,后跟一个或多个空格,后跟一个或多个非’a’字符,后跟一个或多个’字’字符”。 这有两个空格失败的原因是因为\s+与第一个空格匹配,但随后返回第二个空格,然后满足[^a]+ (第二个空格)和\s+部分(第一个空格)。

我认为你可以通过简单地使用posessive量词来修复它,这将是\s++ 。 这告诉\s 不要回馈第二个空格字符。 您可以在此处找到有关Java量词的文档。


作为一个例子,以下是Rubular的两个例子:

  1. \s上使用占有量词 (给出预期结果,来自你描述的内容)
  2. 你当前的正则表达式在[^a\]+\w+周围有单独的分组 。 请注意,第二个匹配组(表示[^a]+ )正在捕获第二个空格字符。