Java的split在使用反斜杠作为分隔符时不会获取空值。

huangapple go评论68阅读模式
英文:

java split does not get empty when backslash separator

问题

我必须根据反斜杠分隔符拆分一个字符串。
我有以下值

value=Alex\\patricia

而中间的值有时是有值的,但在这种情况下没有值,Java会忽略它。
所以,我只有两个标记,而不是三个。

String[] tokens = StringUtils.split(value, '\\');

因此,我得到

tokens[0]=Alex
tokens[1]=Alex=patricia

谢谢

英文:

i have to split a string based on backslash separator
i have the following value

value=Alex\\patricia

and the value in the middle sometimes is valued ,but in this case does not have a value ,it s ignored by java
instead of having three tokens ,i have only two .

String[] tokens = StringUtils.split(value, '\\');

so i get

tokens[0]=Alex
tokens[1]=Alex=patricia

thanks

答案1

得分: 2

尝试只使用标准的Java类

String value = "Alex\\patricia";
String[] tokens = value.split("\\\\");
for (String str : tokens) System.out.println(str);

输出

Alex
patricia
英文:

Try just using standard java classes

    String value="Alex\\patricia";
    String[] tokens = value.split("\\\\");
    for (String str : tokens) System.out.println(str);

output

Alex
patricia

答案2

得分: 1

这是split函数在StringUtils中的工作方式:

相邻的分隔符被视为一个分隔符

你可以使用Java的String split代替。

String value = "Alex\\\\patricia";
String[] tokens = value.split("\\\\"); // 必须进行转义,因为它是正则表达式

示例 jshell 会话:

jshell> String value = "Alex\\\\patricia";
value ==> "Alex\\\\patricia"

jshell> String[] tokens = value.split("\\\\");
tokens ==> String[3] { "Alex", "", "patricia" }
英文:

That's how split from StringUtils works

> Adjacent separators are treated as one separator

You can use Java's String split instead.

String value = "Alex\\\\patricia";
String[] tokens = value.split("\\\\"); // must be escaped since it's a regex

Example jshell session:

jshell> String value="Alex\\\\patricia";
value ==> "Alex\\\\patricia"

jshell> String[] tokens = value.split("\\\\");
tokens ==> String[3] { "Alex", "", "patricia" }

huangapple
  • 本文由 发表于 2020年10月22日 16:25:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/64478190.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定