Java 和 JavaScript 之间的拆分功能似乎有所不同。
我并不完全需要匹配某个正则表达式标准,或者使用 基于前瞻的正则表达式。我的问题在于在拆分正则表达式(这是一组简单的字符而不是表达式)的最终匹配之后尾随空匹配。
下面是我试图实现的输出示例以及我真正得到的结果。
Java
("~#~~#~~#~A~#~B~#~C~#~D~#~E~#~~#~~#~").split("~#~")
/* results with an array of length 8 */ (java.lang.String[]) [, , , A, B, C, D, E]
Javascript
"~#~~#~~#~A~#~B~#~C~#~D~#~E~#~~#~~#~".split("~#~")
/* results with an array of length 11 */ ["", "", "", "A", "B", "C", "D", "E", "", "", ""]
我真的无法对此做出很好的解释,因为我正在使用 Java 应用程序并且拆分给我带来了麻烦,我想要与 JavaScript 中相同的结果。我怎样才能得到它?
最佳答案
关于 split(String regex)
的 Javadoc:
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.
关于 split(String regex, int limit)
的 Javadoc:
If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. 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.
所以... split("~#~", -1)
应该可以解决问题。
关于javascript - Java 与 JavaScript 拆分行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31670822/