Java String replaceAll()

The replaceAll() method replaces each substring that matches the regex of the string with the specified text.

Example


Syntax of replaceAll()

The syntax of the replaceAll() method is:

string.replaceAll(String regex, String replacement)

Here, string is an object of the String class.


replaceAll() Parameters

The replaceAll() method takes two parameters.

  • regex - a regex (can be a typical string) that is to be replaced
  • replacement - matching substrings are replaced with this string

replaceAll() Return Value

The replaceAll() method

  • returns a new string where each occurrence of the matching substring is replaced with the replacement string.

Example 1: Java String replaceAll()

In the above example, "\\d+" is a regular expression that matches one or more digits. To learn more, visit Java regex.


Escaping Characters in replaceAll()

The replaceAll() method can take a regex or a typical string as the first argument. It is because a typical string in itself is a regex.

In regex, there are characters that have special meaning. These metacharacters are:

\ ^ $ . | ? * + {} [] ()

If you need to match substring containing these metacharacters, you can either escape these characters using \ or use the replace() method.

As you can see, when we use the replace() method, we do not need to escape metacharacters. To learn more, visit: Java String replace()


If you need to replace only the first occurrence of the matching substring, use the Java String replaceFirst() method.