How to split a string with multiple delimiters in Scala

1 Answer

0 votes
import scala.util.matching.Regex

object Main {
  def main(args: Array[String]): Unit = {
    val s = "aaa : bbb / ccc . ddd ? eee&fff - ggg_hhh | iii \n jjj"
    
    // Define the delimiters (comma, space, exclamation mark, question mark)
    val delimiters = new Regex("[,\\s!?\\-|/\\n._:&]+") 
    
    // Split the string using the defined delimiters
    val words = delimiters.split(s)
    
    words.foreach(println)
  }
}



/*
run:

aaa
bbb
ccc
ddd
eee
fff
ggg
hhh
iii
jjj
 
*/

 



answered Mar 4, 2025 by avibootz
...