我对 Java 中正则表达式的拆分方法感到困惑。这是一个相当理论化的问题,我无法弄明白。
我找到了这个答案:Java split by \\S 但是使用\\s 而不是\\S 的建议并没有解释这里发生的事情。
为什么:quote.split("\\S") 在情况 A 中有 2 个结果,在情况 B 中有 8 个结果?
案例A)
String quote = " x xxxxxx";
String[] words = quote.split("\\S");
System.out.print("\\S >>\t");
for (String word : words) {
System.out.print(":" + word);
}
System.out.println(words.length);
结果:
\\S >> : : 2
案例 B)
String quote = " x xxxxxx ";
String[] words = quote.split("\\S");
System.out.print("\\S >>\t");
for (String word : words) {
System.out.print(":" + word);
}
System.out.println(words.length);
结果:
\\S >> : ::::::8
如果能理解这里发生的事情,那就太好了。提前致谢。
最佳答案
正如 Jongware 所注意到的,String.split(String) 的文档说:
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
所以它的工作方式有点像这样:
"a:b:::::".split(":") === removeTrailing([a,b,,,,,]) === [a,b]
"a:b:::::c".split(":") === removeTrailing([a,b,,,,,c]) === [a,b,,,,,c]
在你的例子中:
" x xxxxxx".split("\\S") === removeTrailing([ , ,,,,,,]) === [ , ]
" x xxxxxx ".split("\\S") === removeTrailing([ , ,,,,,, ]) === [ , ,,,,,, ]
要将多个定界符合并为一个,请使用 \S+
模式。
" x xxxxxx".split("\\S+") === removeTrailing([ , ,]) === [ , ]
" x xxxxxx ".split("\\S+") === removeTrailing([ , , ]) === [ , , ]
如评论中所建议的,为了保留尾随的空字符串,我们可以使用重载版本的 split 方法 ( String.split(String, int) ) 并传递一个负数作为限制。
"a:b:::::".split(":", -1) === [a,b,,,,,]
关于Java Regex Split\\S --> String split method\\S 的奇怪结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25580335/