28

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 4

84

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)
Sign up to request clarification or add additional context in comments.

4 Comments

this should be the answer. Moritz strategy of creating a regex works, but this simple solution is better.
this answer actually answers the question; the currently accepted answer describes a theory that could work, but doesn't describe the actual answer to the asked question.
There's a problem with split: when you try "::".split("::") you get Nil, but should List("","")
@Vitamon If that were so, then "aaaaa".split("a") => List("", "", "", "", "", "") -- which for most purposes doesn't offer any useful information. Would rather interpret as empty.
30

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 Comments

Ah yes. I was convinced it took a Regex or a Char, not a String, so it kept complaining.
I suggest using \Q and \E instead of doing individual escaping. Just add \Q to the beginning (or \\Q, as needed), and a \E to the end.
@DanielC.Sobral Great idea - any way to escape a string stored in a var (constant)?
@Rubistro You can use scala.util.matching.Regex.quote, or Java's equivalent method.
@DanielC.Sobral I found that java.util.regex.Pattern.quote(str) will do that to an arbitrary String literal (surround with \Q and \E).
12

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

Comments

5

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.