How to replace regular expression patterns in strings in Scala

Scala String FAQ: How do I replace a regular expression (regex) pattern in a String in Scala?


Because a 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

Another approach is to 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 replaceFirst method:

scala> val result = "123".replaceFirst("[0-9]", "x")
result: java.lang.String = x23

You can also use replaceFirstIn with a Regex:

scala> val regex = "H".r
regex: scala.util.matching.Regex = H

scala> val result = regex.replaceFirstIn("Hello world", "J")
result: String = Jello world


As a quick summary, if you need to search for a regex in a String and replace it in Scala, the replaceAll, replaceAllIn, replaceFirst, and replaceFirstIn methods will help solve the problem.