Java正则表达式:如何匹配一个或多个空格字符

2024-01-09

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

问题其实是因为回溯 http://www.regexguru.com/2008/04/unintended-backtracking-can-bite-you/。你的正则表达式:

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

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

我认为你可以通过简单地使用所有格量词来解决它,这将是\s++。这告诉\s not返回第二个空格字符。你可以找到关于Java量词的文档here http://docs.oracle.com/javase/tutorial/essential/regex/quant.html.


作为说明,以下是 Rubular 的两个示例:

  1. 使用所有格量词\s http://rubular.com/r/1bZXssn7RH(根据您的描述给出预期结果)
  2. 您当前的正则表达式具有单独的分组[^a\]+ and \w+ http://rubular.com/r/kJA2txx10c。请注意,第二个比赛组(代表[^a]+) 正在捕获第二个空格字符。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java正则表达式:如何匹配一个或多个空格字符 的相关文章

随机推荐