How to replace regex patterns in Scala strings (find and replace)

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.”

Problem

You want to search for regular-expression patterns in a Scala string, and replace them.

Solution

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

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

See Also

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations: