Scala regex split example

Scala regular expressions have a “split” function on them, which applies the regular expression to a string, breaking it up into an array of values from the original.

For instance, in this example we’ll use commas as delimiters:

",".r.split("1,0,3")
res14: Array[String] = Array(1, 0, 3)

If you want to match repeated characters, as expected, you can use the “+” in the regular expression, and you’ll get the same result:

",+".r.split("1,0,,,,3")
res16: Array[String] = Array(1, 0, 3)

Note that you don’t want to use “*” on the string, as this matches 0 or more characters, so you’ll just get an array with every character in an entry:

 
",*".r.split("1,0,,,,3")
res17: Array[String] = Array(1, "", 0, "", 3)

If you include a slash, you will need to escape it, like so:

"\\w+".r.split("1b0a3")

Leave a Reply

Your email address will not be published. Required fields are marked *