1.7. Replacing Patterns in Strings

Problem

You want to search for regular-expression patterns in a 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

Recipe 1.6 for examples of how to find patterns in strings

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.