Scala: How to replace all consecutive underscore w

2019-09-22 05:15发布

问题:

I want to replace all the consecutive underscores with a single space. This is the code that I have written. But it is not replacing anything. Below is the code that I have written. What am I doing wrong?

import scala.util.matching.Regex

val regex: Regex = new Regex("/[\\W_]+/g")
val name: String = "cust_id"
val newName: String = regex.replaceAllIn(name, " ")
println(newName)

Answer: "cust_id"

回答1:

You could use replaceAll to do the job without regex :

val name: String = "cust_id"
val newName: String = name.replaceAll("_"," ")
println(newName)


回答2:

The slashes in your regular expression don't belong there.

new Regex("[\\W_]+", "g").replaceAllIn("cust_id", " ")
// "cust id"


回答3:

A string in Scala may be treated as a collection, hence we can map over it and in this case apply pattern matching to substitute characters, like this

"cust_id".map {
  case '_' => " "
  case c   => c
}.mkString

Method mkString glues up the vector of characters back onto a string.



标签: regex scala