简体   繁体   English

Scala String拆分bizareness

[英]Scala String split bizareness

I wrote this code 我写了这段代码

val line = "Aaa Bbb Ccc"
line.split(" ")

which produces the following output as expected: 它按预期产生以下输出:

res31: Array[String] = Array(Aaa, Bbb, Ccc)

I change the code slightly : 稍微更改了代码:

val line = "Aaa|Bbb|Ccc"
line.split("|")

And now I don't understand the output: 现在我不明白输出:

res30: Array[String] = Array("", A, a, a, |, B, b, b, |, C, c, c)

Why did this happen? 为什么会这样?

split takes a string representing the regex to split on - "|" split使用表示正则表达式的字符串来分割 - “|” is a regex for the empty string or another empty string, so it splits between every character. 是空字符串或另一个空字符串的正则表达式,因此它在每个字符之间分割。 You need to escape the | 你需要逃避| :

line.split("\\|")

alternatively you can use the overload which takes a Char parameter to split on (defined in StringOps ): 或者你可以使用带有Char参数的重载(在StringOps定义):

line.split('|')

Pipe "|" 管道“|” is a regex character that means either of two options. 是一个正则表达式字符,意味着两个选项之一。 In that case either empty or empty. 在这种情况下,空或空。

Try escaping it to use it as a character: 尝试转义它以将其用作角色:

val line = "Aaa|Bbb|Ccc"
line.split("\\|")

res0: Array[String] = Array(Aaa, Bbb, Ccc)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM