Gaurav
Gaurav

Reputation: 173

How to use split function in scala

I have String

val s1 = "dog#$&cat#$&cow#$&snak"
val s2 = s1.split()

how to split string into words

Upvotes: 0

Views: 156

Answers (1)

The fourth bird
The fourth bird

Reputation: 163342

For a precise split, you could use #\\$& to match all 3 characters where the dollar sign has to be escaped, and the backslash itself also has to be escaped.

val s1= "dog#$&cat#$&cow#$&snak"
val s2= s1.split("#\\$&")

Output

s2: Array[String] = Array(dog, cat, cow, snak)

A broader pattern could be using \\W+ to match 1+ times any character except a word character.

Upvotes: 2

Related Questions