This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a short solution from the book, Recipe 1.8, “Replacing Patterns in Scala Strings.”
You want to search for regular-expression patterns in a Scala string, and replace them.
String is immutable, you can’t perform find-and-replace operations directly on it, but you can create a new
String that contains the replaced contents. There are several ways to do this.
You can call
replaceAll on a
String, remembering to assign the result to a new variable:
scala> val address = "123 Main Street".replaceAll("[0-9]", "x") address: java.lang.String = xxx Main Street
You can create a regular expression and then call
replaceAllIn on that expression, again remembering to assign the result to a new string:
scala> val regex = "[0-9]".r regex: scala.util.matching.Regex = [0-9] scala> val newAddress = regex.replaceAllIn("123 Main Street", "x") newAddress: String = xxx Main Street
To replace only the first occurrence of a pattern, use the
scala> val result = "123".replaceFirst("[0-9]", "x") result: java.lang.String = x23
You can also use
replaceFirstIn with a
scala> val regex = "H".r regex: scala.util.matching.Regex = H scala> val result = regex.replaceFirstIn("Hello world", "J") result: String = Jello world