Java Regex Split\\S --> String split method\\S 的奇怪结果

标签 java regex string split

我对 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/

相关文章:

regex - Linux sed - 删除不以特定字符开头的单词

java - 数组和字符串充当对象

java - Java 中有效且漂亮的字符串条件

java - OpenGL 旋转框

路由器中没有转发端口的Java程序

java - 在包中运行所有测试时出现 JUnit java.lang.OutOfMemoryError

java - 创建正则表达式匹配数组

javascript - 正则表达式 : Allow letters, 数字和空格(至少有一个字母或数字)

java - 如何在不使用任何库的情况下用Java创建图形对象?

c++ - 为什么这个 C++ 程序会打印不相关的字符?