String Replace
Replacing text means producing a new string in which some characters or substrings have been swapped for others. Java provides four replacement methods: two that treat their arguments as literal text and two that treat them as regular expressions. Knowing which kind you are using avoids the most common surprises, especially with characters like ., $, and ``.
| Method | Search argument | Replaces |
|---|---|---|
replace(char old, char new) | A single character | Every occurrence |
replace(CharSequence target, CharSequence replacement) | Literal text | Every occurrence |
replaceAll(String regex, String replacement) | Regular expression | Every match |
replaceFirst(String regex, String replacement) | Regular expression | The first match only |
As with all String methods, the original string is never modified; each method returns a new string.
replace with Characters
String date = "2026-11-11";
String slashed = date.replace('-', '/'); // "2026/11/11"
System.out.println(date); // 2026-11-11 (unchanged)
replace with Text
String msg = "Hello NAME, welcome NAME!";
String out = msg.replace("NAME", "Ada"); // "Hello Ada, welcome Ada!"
Despite the name difference from replaceAll, replace replaces every occurrence, not just the first. The search text and the replacement are both literal: no character has a special meaning.
"a.b.c".replace(".", "-"); // "a-b-c"
"cost: $5".replace("$5", "$7"); // "cost: $7"
Replacements are applied left to right without overlap, and the result is not re-scanned:
"aaa".replace("aa", "b"); // "ba": the first two a's match; the third is left alone
To delete text, replace it with an empty string:
"(044) 2345-6789".replace("(", "").replace(")", "").replace("-", ""); // "044 23456789"
replaceAll: Regular Expressions
replaceAll interprets its first argument as a regular expression, which lets one call match a whole class of text:
"a1b22c333".replaceAll("\\d+", "#"); // "a#b#c#" runs of digits
" Too many spaces\there ".strip().replaceAll("\\s+", " "); // "Too many spaces here"
"4111-1111-1111-1234".replaceAll("\\D", ""); // "4111111111111234" non-digits removed
Common patterns:
| Pattern | Matches |
|---|---|
|