String.replaceAll()
Replaces every match of a regular expression.
Available since: Java 1.4
Syntax
public String replaceAll(String regex, String replacement)Parameters
| Parameter | Type | Description |
|---|---|---|
| regex | String | The regular expression to search for. |
| replacement | String | The 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 spacesGroups 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.2025Removing everything except digits:
void main() {
IO.println("Order #A-1042/7".replaceAll("[^0-9]", ""));
}Output:
10427Notes
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
- How to check if a string is a palindrome
- How to convert camelCase to snake_case and back
- How to create a slug from a string
- How to extract numbers from a string
- How to find matches with a regular expression
- How to remove all whitespace from a string
- How to replace text in a string
- How to trim whitespace from a string
In the tutorial
- Regular expressions — Regular expressions in Java: matches, replaceAll, splitting by a pattern, the Pattern and Matcher classes, groups and escaping backslashes.