Java 空字符串和单个分隔符字符串的字符串拆分行为

Java 空字符串和单个分隔符字符串的字符串拆分行为,java,scala,Java,Scala,这是一项后续行动 问题在下面的第二行 "".split("x"); //returns {""} // ok "x".split("x"); //returns {} but shouldn't it return {""} because it's the string before "x" ? "xa".split("x"); //returns {"", "a"} // see?, here "" is the first string returned "ax".sp

这是一项后续行动

问题在下面的第二行

"".split("x");   //returns {""}   // ok
"x".split("x");  //returns {}   but shouldn't it return {""} because it's the string before "x" ?
"xa".split("x"); //returns {"", "a"}    // see?, here "" is the first string returned
"ax".split("x"); //returns {"a"}

否,因为根据“将丢弃尾随的空字符串”

根据
java.util.regex.Pattern
使用的
String.split(…)
模式

"".split("x");   // returns {""} - valid - when no match is found, return the original string
"x".split("x");  // returns {} - valid - trailing empty strings are removed from the resultant array {"", ""}
"xa".split("x"); // returns {"", "a"} - valid - only trailing empty strings are removed
"ax".split("x"); // returns {"a"} - valid - trailing empty strings are removed from the resultant array {"a", ""}

要包含尾随的空字符串,请使用的其他实现


请参阅“当分隔符出现在字符串末尾时split()中的错误”这就是Google Guava创建com.Google.common.base.splitter的原因。那么为什么不在第一行中丢弃它呢?(在空字符串上拆分)这应该理解为“结果数组末尾的空字符串将被丢弃”。我猜它将空字符串视为第一个标记,然后在它之后拆分,因此从技术上讲,它还是一个前导空字符串,来自JavaDoc:如果表达式与输入的任何部分都不匹配,则生成的数组只有一个元素,即该字符串。“可能它不一致,但它按照承诺的方式工作。所以它的行为正确,因为它调用的方法……就是这样的?我想知道当我用这样的论点结束下一个bug报告时,老板会说什么。@Kim Stebel,
SO
都不是bug追踪器,我也不应该为它修复bug。这篇文章基本上要求澄清,而不是解决方案,我只是试图说明
split
方法为何会出现这种情况。别紧张。
"".split("x", -1);   // returns {""} - valid - when no match is found, return the original string
"x".split("x", -1);  // returns {"", ""} - valid - trailing empty strings are included in the resultant array {"", ""}
"xa".split("x", -1); // returns {"", "a"} - valid
"ax".split("x", -1); // returns {"a", ""} - valid - trailing empty strings are included in the resultant array {"a", ""}