Govind Singh
Govind Singh

Reputation: 15490

Split string by two conditions

I have to split this string from

val str="s: saturday, sunday, solar, selfie"

into an Array

s,saturday,sunday,solar,selfie

in scala 2.10

Upvotes: 3

Views: 18162

Answers (3)

Tushar Thapliyal
Tushar Thapliyal

Reputation: 11

str=str.replaceAll("[^a-zA-Z0-9]",""); String[] array=str.split("\\s"); //use this to first remove all the special characters and then splitting it into string array

Upvotes: 1

Beryllium
Beryllium

Reputation: 12998

From the perspective of the string to be split:

val text = "s: saturday, sunday, solar, selfie"
val words = text.split("[:,] ")

Scala uses the same method as in java.lang.String.


As an alternative, from the perspective of the regex:

val str = "s: saturday, sunday, solar, selfie"
val regex = "[:,] ".r
val words = regex.split(str)

Possibly interesting if the regex is complex, and you want to reuse it multiple times. The .r is a method in StringLike which returns a Regex.

Upvotes: 3

Peter Lawrey
Peter Lawrey

Reputation: 533530

in Java you would write

String text = "s: saturday, sunday, solar, selfie";
String[] words = text.split("[:,] ");

This will split by an : or , followed by a space. If the space is optional you could use "[:,] ?"

Upvotes: 7

Related Questions