Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Matcher.replaceAll()

Replaces every match with a string or with the result of a function that receives each match.

Available since: Java 1.4

Syntax

public String replaceAll(Function<MatchResult, String> replacer)

Parameters

ParameterTypeDescription
replacerFunction<MatchResult, String> / StringA replacement string ($1 is a group) or a function that returns the replacement for a match.

Return value

StringA new string.

Examples

A computed replacement — doubling every number:

void main() {
    Matcher m = Pattern.compile("\\d+").matcher("3 apples and 12 pears");
    String result = m.replaceAll(r -> String.valueOf(Integer.parseInt(r.group()) * 2));
    IO.println(result);
}

Output:

6 apples and 24 pears

A replacement with a group: capitalizing every word:

void main() {
    Matcher m = Pattern.compile("\\b(\\w)(\\w*)").matcher("hello big world");
    IO.println(m.replaceAll(r -> r.group(1).toUpperCase() + r.group(2)));
}

Output:

Hello Big World

Notes

A replacement string with $1, $2 groups is simpler to pass to String.replaceAll(). The function form (Java 9) is for when the replacement must be computed. If the function result contains $ or \, wrap it in Matcher.quoteReplacement().

See also

  • String.replaceAll() — Replaces every match of a regular expression.
  • Matcher.group() — Returns the text of the current match or of one of its parenthesized groups.
  • Pattern.compile() — Compiles a regular expression into a Pattern object that can be reused many times.

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.