string 如何在 Scala 中按字符串拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5522572/
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
How to split a string by a string in Scala
提问by Félix Saparelli
In Ruby, I did:
在 Ruby 中,我做了:
"string1::string2".split("::")
In Scala, I can't find how to split
using a string, not a single character.
在 Scala 中,我找不到如何split
使用字符串,而不是单个字符。
回答by Janx
The REPL is even easier than Stack Overflow. I just pasted your example as is.
REPL 甚至比 Stack Overflow 更容易。我只是按原样粘贴了您的示例。
Welcome to Scala version 2.8.1.final (Java HotSpot Server VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.
Welcome to Scala version 2.8.1.final (Java HotSpot Server VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.
scala> "string1::string2".split("::")
res0: Array[java.lang.String] = Array(string1, string2)
回答by Moritz
In your example it does not make a difference, but the String#split
method in Scala actually takes a String
that represents a regular expression. So be sure to escape certain characters as needed, like e.g. in "a..b.c".split("""\.\.""")
or to make that fact more obvious you can call the split method on a RegEx
: """\.\.""".r.split("a..b.c")
.
在您的示例中,它没有任何区别,但String#split
Scala 中的方法实际上采用String
表示正则表达式的 a 。所以一定要根据需要对某些字符进行转义,例如 in"a..b.c".split("""\.\.""")
或者为了使这一事实更加明显,您可以在RegEx
:上调用 split 方法"""\.\.""".r.split("a..b.c")
。
回答by Fabian Steeg
That line of Ruby should work just like it is in Scala too and return an Array[String]
.
那行 Ruby 也应该像在 Scala 中一样工作,并返回一个Array[String]
.
回答by haffla
If you look at the Java implementationyou see that the parameter to String#split
will be in fact compiled to a regular expression.
如果您查看Java 实现,您会发现 to 参数String#split
实际上将被编译为正则表达式。
There is no problem with "string1::string2".split("::")
because ":" is just a character in a regular expression, but for instance "string1|string2".split("|")
will not yield the expected result. "|" is the special symbol for alternation in a regular expression.
没有问题,"string1::string2".split("::")
因为“:”只是正则表达式中的一个字符,但例如"string1|string2".split("|")
不会产生预期的结果。“|” 是正则表达式中交替的特殊符号。
scala> "string1|string2".split("|")
res0: Array[String] = Array(s, t, r, i, n, g, 1, |, s, t, r, i, n, g, 2)