javascript - Java 与 JavaScript 拆分行为

标签 javascript java split

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/

相关文章:

c# - 将String解析为多个可变长度的String(C#)

java - 一个简单的 string.split() 出了可怕的错误

javascript - javascript onclick 处理程序中的性能问题

Javascript:运行函数后添加 'false'

java - 无法在任何存储库中找到资源 'com.ibm.icu:icu4j:pom:3.4.1'

ruby - 如何将范围拆分为 N 个部分

javascript - 异步 promise 的问题

javascript - 如何在元素不超出父边界的情况下过渡高度?

java - 向 Swagger UI 添加基本身份验证

java - 使用 ArrayList 时出现明显错误,但遵循给定的语法(Stanford CS106A HangmanLexicon)