java - Java 7 中的字符串拆分(非空格的正则表达式)

标签 java regex split

<分区>

String test="I am preparing for OCPJP";
String[] tokens=test.split("\\S");
System.out.println("length:"+tokens.length);
for(String s:tokens) {
  System.out.print("["+s+"]");
}
System.out.println();

输出:

length:16
[][ ][][ ][][][][][][][][][ ][][][ ]

现在我将 split(regex) 更改为 split(regex,limit)

输出:

length:21
[][ ][][ ][][][][][][][][][ ][][][ ][][][][][]

你能告诉我为什么这个结果不同吗?非常感谢!

最佳答案

Javadocs for the 2-arg overload of split状态:

If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

Javadocs for the 1-arg overload of split状态:

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.

而 1-arg,无限制重载等同于 0 的限制。对于非零限制,尾随的空字符串不再被丢弃。不再丢弃的那 5 个尾随空字符串对应于在“OCPJP”中找到的非空格。

关于java - Java 7 中的字符串拆分(非空格的正则表达式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23689770/

相关文章:

java - 你能在字符串拆分中使用零宽度匹配正则表达式吗?

php - 我如何使用带有简单字符串和通配符的 php 的 preg_replace?

python - 如何将列表拆分为零值和非零值的子列表

python - 如何在python中拆分字符串

java - 如何在 java 中使用 "."作为 String.split() 的分隔符

java - 从 XML 中多次提取数据的最佳且优化的方法是什么?

java - 锁定写入 HashMap

java - 如何使 JFreeChart 保持纵横比?

java - 如何使用 SpEL 设置注释字段来处理值

c# - Sql Server 中的正则表达式