How to split a string by a string in Scala

In Ruby, I did:

"string1::string2".split("::")

In Scala, I can't find how to split using a string, not a single character.

4 Answers

The REPL is even easier than Stack Overflow. I just pasted your example as is.

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)
4

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").

5

That line of Ruby should work just like it is in Scala too and return an Array[String].

If you look at the Java implementation you see that the parameter to String#split will be in fact compiled to a regular expression.

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.

scala> "string1|string2".split("|")
res0: Array[String] = Array(s, t, r, i, n, g, 1, |, s, t, r, i, n, g, 2)

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like