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的两个例子:
- 在
\s
上使用占有量词 (给出预期结果,来自你描述的内容) - 你当前的正则表达式在
[^a\]+
和\w+
周围有单独的分组 。 请注意,第二个匹配组(表示[^a]+
)正在捕获第二个空格字符。
- 如何重新打开Java套接字
- 使用parallelstream()在Java 8中填充Map是否安全
- 如何在Jersey 2.4filter中获取资源注释?
- 如何使用GSON / JSON将字符串数组转换为对象?
- kCFStreamPropertySocketSecurityLevel到kCFStreamSocketSecurityLevelNegotiatedSSL导致连接到Java的OSStatus errSSLXCertChainInvalid(-9807)
- Runtime.getRuntime()。exec(“C:\ cygwin \ bin \ bash.exe”)没有输入读取
- 如何正确地为数据结构中的图像设置动画而不是获取ConcurrentModificationException
- 何时编写静态方法与实例方法的编码是否有经验法则?
- 找到所有哈密顿循环