scala string.split 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11284771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
scala string.split does not work
提问by riship89
Following is my REPL output. I am not sure why string.split does not work here.
以下是我的 REPL 输出。我不确定为什么 string.split 在这里不起作用。
val s = "Pedro|groceries|apple|1.42"
s: java.lang.String = Pedro|groceries|apple|1.42
scala> s.split("|")
res27: Array[java.lang.String] = Array("", P, e, d, r, o, |, g, r, o, c, e, r, i, e, s, |, a, p, p, l, e, |, 1, ., 4, 2)
回答by Rex Kerr
If you use quotes, you're asking for a regular expression split. |is the "or" character, so your regex matches nothing or nothing. So everything is split.
如果您使用引号,则是在要求进行正则表达式拆分。 |是“或”字符,因此您的正则表达式不匹配或不匹配。所以一切都分裂了。
If you use split('|')or split("""\|""")you should get what you want.
如果你使用split('|')orsplit("""\|""")你应该得到你想要的。
回答by Esko
|is a special regular expressioncharacter which is used as a logical operator for ORoperations.
|是一个特殊的正则表达式字符,用作操作的逻辑运算符OR。
Since java.lang.String#split(String regex);takes in a regular expression, you're splitting the string with "none OR none", which is a whole another speciality about regular expression splitting, where noneessentially means "between every single character".
由于java.lang.String#split(String regex); 接受一个正则表达式,你用"none OR none"分割字符串,这是关于正则表达式分割的另一个专长,其中none本质上意味着“在每个单个字符之间”。
To get what you want, you need to escape your regex pattern properly. To escape the pattern, you need to prepend the character with \and since \is a special Stringcharacter (think \tand \rfor example), you need to actually double escape so that you'll end up with s.split("\\|").
为了得到你想要的东西,你需要正确地转义你的正则表达式模式。逃脱模式,你需要预先考虑性格\既然\是一个特殊String字符(想\t和\r为例),实际上你需要双逃逸,让你结了s.split("\\|")。
For full Java regular expression syntax, see java.util.regex.Pattern javadoc.
有关完整的 Java 正则表达式语法,请参阅java.util.regex.Pattern javadoc。
回答by Jari
Split takes a regex as first argument, so your call is interpreted as "empty string or empty string". To get the expected behavior you need to escape the pipe character "\\|".
Split 将正则表达式作为第一个参数,因此您的调用被解释为“空字符串或空字符串”。要获得预期的行为,您需要对管道字符“\\|”进行转义。

