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
| Parameter | Type | Description |
|---|---|---|
| replacer | Function<MatchResult, String> / String | A 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 pearsA 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 WorldNotes
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.