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
- See Recipe 1.7, “How to find regex patterns in Scala strings,” for examples of how to find patterns in strings
- The Scala Regex class
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |