Java replaceAll() methods: String.replaceAll(), Matcher.replaceAll() and related methods

Java provides a number of methods for performing search and replace om strings:

String.replaceAll()

The simplest way to perform a "find and replace" operation on a Java String is to call the replaceAll() method on the given String. Because Java Strings are immutable, this method will return a new string> with the sought substring or pattern replaced. The main mistake that programmers make when using String.replaceAll() is to forget that the search string is actually a regular expression. So you need to be careful to:

Here is an example of using String.replaceAll() to replace instances of "USD" in a string with a dollar sign. Because the search string "USD" is a fixed string and we know that it does not have any special regular expression characters, we can simply write the string in its raw form:

str = str.replaceAll("USD",
Matcher.quoteReplacement("$"));

On the other hand, here is an example where the string being searched for is not fixed. In this case, we cannot be sure that it does not contain a special character, and so must wrap it in Pattern.quote():

public String replaceCurrencySymbols(String str, String letterCode, String symbol) {
  return str.replaceAll(Pattern.quote(letterCode),
    Matcher.quoteReplacement(symbol));
}

For more information, see the page on search and replace in Java.

String.replaceFirst()

The replaceFirst() method works in a very similar way to replaceAll(), but returns a new string with just the first instance of the pattern or substring replaced with the replacement string, as you might expect. The same precautions apply: remember to use Pattern.quote() and Matcher.quoteReplacement() as necessary.

When and how to use Matcher.replaceAll()

For occasional use, String.replaceAll() is an extremely convenient way of replacing one substring with another in a given string. However, it is inefficient because it generally needs to compile the regular expression and create a brand new Pattern and Matcher instance every single time.

To use Matcher.replaceAll(), we follow the general procedure for using Pattern and Matcher:

The following method takes a list of strings and, for each string, replaces all instances of a digit with the the string <digit>:

  private static final Pattern DIGIT_PATTERN =
  Pattern.compile("\\d");
	
  public void replacDigits(List<String> strs) {
    for (int i = 0; i < strs.length(); i++) {
      String str = strs.get(i);
      Matcher m = DIGIT_PATTERN.matcher(str);
	  str = m.replaceAll("");
	  strs.set(i, str);
    }
  }

Notice that it is safe (and generally advisable) to share the same Pattern object across mutliple calls and mutliple threads.

In this case, the substring that we want to find is a regular expression: \d matches a single digit (we could also write [0-9]).

Using replaceAll() with different replacement strings

For more flexible search and replace operations, you can use replaceAll() with a lambda expression that allows the replacement string to be determined dynamically rather than being the same fixed replacement string.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.