Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.replaceAll()

Replaces every match of a regular expression.

Available since: Java 1.4

Syntax

public String replaceAll(String regex, String replacement)

Parameters

ParameterTypeDescription
regexStringThe regular expression to search for.
replacementStringThe replacement string. In it $1, $2 insert the captured groups.

Return value

StringA new string with the replacements.

Examples

Several spaces in a row become one:

void main() {
    String text = "too    many   spaces";
    IO.println(text.replaceAll("\\s+", " "));
}

Output:

too many spaces

Groups in the replacement — reordering date parts:

void main() {
    String date = "2025-03-14";
    IO.println(date.replaceAll("(\\d{4})-(\\d{2})-(\\d{2})", "$3.$2.$1"));
}

Output:

14.03.2025

Removing everything except digits:

void main() {
    IO.println("Order #A-1042/7".replaceAll("[^0-9]", ""));
}

Output:

10427

Notes

A backslash in a Java string is written twice: the regular expression \s+ looks like "\\s+" in code. To replace only the first match use replaceFirst().

The $ and \ characters are special in the replacement. To insert them literally, wrap the replacement in Matcher.quoteReplacement().

See also

  • String.replace() — Replaces every occurrence of a substring or a character with another string.
  • String.matches() — Checks whether the whole string matches a regular expression.
  • Matcher.replaceAll() — Replaces every match with a string or with the result of a function that receives each match.
  • Pattern.compile() — Compiles a regular expression into a Pattern object that can be reused many times.

Related recipes

In the tutorial

  • Regular expressions — Regular expressions in Java: matches, replaceAll, splitting by a pattern, the Pattern and Matcher classes, groups and escaping backslashes.

Thanks for reading!

Donate to the site — we work hard for you.