Java regex replace all
How Java's replaceAll works, how it differs from replace and Matcher.replaceAll, which replacement characters are special, and how Unicode affects the results.
Replacing every regex match in a Java string usually means calling String.replaceAll or Matcher.replaceAll. Both scan the input for every match of a regular expression and return a new string with each match substituted. This review covers when that approach fits, what it changes in the text, and where the result can surprise you.
Is a regex replace-all the right tool for your task?
Use a regex replace-all when the text you want to change follows a pattern rather than a fixed string. Examples include runs of whitespace, digit sequences, date formats, or repeated punctuation. The main benefit is that a single call handles every variant the pattern describes. The decisive tradeoff is that both arguments carry special syntax. The first argument is a regular expression, and the replacement string treats dollar signs and backslashes as instructions. Input that contains those characters can produce wrong output or throw an exception.
If you only need to swap one fixed piece of text for another, use plain String.replace. Despite its name, String.replace also changes every occurrence. It treats both arguments as literal text, so you avoid escaping problems and the cost of compiling a regex.
What the transformation actually changes
A regex replace-all changes the stored characters. Java strings are immutable, so the original string is left as it was and a new string holds the result. This differs from visual effects such as CSS styling, mirrored-looking glyphs or Unicode "font" substitutions, which change how text looks or which look-alike characters are used. After a replace-all, the new characters are the text. Anything that later reads the string, such as a search index, a parser, a database or a screen reader, sees exactly what the replacement produced.
| Method | How the first argument is read | What gets replaced | Notes |
| String.replace(CharSequence, CharSequence) | Literal text | Every occurrence | No regex syntax; no special characters in the replacement |
| String.replaceAll(String, String) | Regular expression | Every match | Compiles the pattern on each call; $ and \ are special in the replacement |
| String.replaceFirst(String, String) | Regular expression | First match only | Same replacement rules as replaceAll |
| Matcher.replaceAll(String) | Precompiled Pattern | Every match | Lets you reuse one compiled pattern across many inputs |
| Matcher.replaceAll(Function<MatchResult, String>) | Precompiled Pattern | Every match, with a computed replacement | Available since Java 9; the returned string is still parsed for $ and \ |
String s = "a1b22c333";
String r = s.replaceAll("\\d+", "#"); // "a#b#c#"
String date = "2026-10-31";
date.replaceAll("(\\d{4})-(\\d{2})-(\\d{2})", "$3/$2/$1");
// "31/10/2026"
date.replaceAll("(?<y>\\d{4})-(?<m>\\d{2})-(?<d>\\d{2})", "${d}/${m}/${y}");
// same result, using named groups
In Java source code, a regex backslash must itself be escaped. That is why the pattern for one or more digits is written as "\d+". In the replacement, $1 or ${name} inserts a captured group.
Escaping literal patterns and replacements
If the replacement comes from user input, configuration or data, wrap it in Matcher.quoteReplacement so that dollar signs and backslashes are inserted as written. If the pattern itself is literal text that happens to contain regex metacharacters, wrap it in Pattern.quote. In that second case, String.replace is often the simpler choice.
String price = "Total: AMOUNT";
price.replaceAll("AMOUNT", Matcher.quoteReplacement("$5.00"));
// "Total: $5.00"
// price.replaceAll("AMOUNT", "$5.00") throws: "$5" is read as a reference to group 5
"1+1=2".replaceAll(Pattern.quote("1+1"), "two"); // "two=2"
"1+1=2".replace("1+1", "two"); // same result, no regex involved
Reusing a pattern and computing replacements
String.replaceAll compiles its regex every time it is called. In a loop or on a hot path, compile the pattern once and call Matcher.replaceAll on each input. Since Java 9, you can also pass a function that builds each replacement from the match. The string that function returns is still interpreted as a replacement, so quote it if it can contain $ or .
private static final Pattern SPACES = Pattern.compile("\\s+");
String tidy = SPACES.matcher(input).replaceAll(" ");
Pattern num = Pattern.compile("\\d+");
String doubled = num.matcher("a2b10")
.replaceAll(m -> String.valueOf(Integer.parseInt(m.group()) * 2));
// "a4b20"
Unicode: code points, combining marks and emoji
Java's regex engine matches by code point, so a dot will not split a surrogate pair. However, a single visible character can still be several code points. Examples include a letter followed by a combining accent and many emoji sequences. A dot matches each code point separately. The \X construct, available since Java 9, matches a grapheme cluster instead. Exact grapheme boundaries for newer emoji sequences depend on the Unicode version your JDK implements, so test on the JDK you deploy. Normalizing input with java.text.Normalizer before matching can also reduce mismatches between precomposed and decomposed forms.
String s = "cafe\u0301"; // displays as "café" (decomposed)
s.replaceAll(".", "*"); // "*****" the combining mark is a separate match
s.replaceAll("\\X", "*"); // "****" one match per grapheme cluster
"naïve".replaceAll("\\w+", "X"); // "XïX" \w is ASCII-only by default
"naïve".replaceAll("(?U)\\w+", "X"); // "X" UNICODE_CHARACTER_CLASS enabled
Case-insensitive matching with (?i) covers only US-ASCII by default. Add the UNICODE_CASE flag, written inline as (?iu), when matching non-ASCII letters. By default, a dot does not match line terminators, and ^ and $ refer to the whole input. Use the DOTALL and MULTILINE flags when your pattern needs to cross or anchor to lines.
Will the result stay readable after copying or sharing?
Because a replace-all produces ordinary stored characters, copying or sharing the output carries exactly those characters. There is no hidden styling layer that could be lost. Readability problems come from what the pattern changes:
- Collapsing whitespace or line breaks changes layout and can merge lines that were meant to stay separate.
- Stripping invisible characters can alter display order in mixed-direction text, because zero-width and bidirectional control characters affect how right-to-left and left-to-right runs are arranged.
- Inserting decorative symbols adds characters that search, editing tools and screen readers treat as real content.
- Case folding or broad character-class replacements can change meaning, for example in identifiers, codes or names.
Keep an untouched copy of the original text wherever the replacement exists only for display or for one consumer. That lets you search, edit or present a plain-text equivalent without reversing the replacement.
Common mistakes
- Assuming String.replace changes only the first occurrence; it replaces all of them, literally.
- Passing unescaped user text as the pattern or the replacement.
- Forgetting that replaceAll returns a new string and discarding the result.
- Recompiling the same regex inside a loop through String.replaceAll.
- Using a dot or \w on international text without considering combining marks, grapheme clusters or Unicode flags.
- Using a pattern that can match the empty string: "abc".replaceAll("", "-") returns "-a-b-c-".
Evidence gaps
This review relies on the documented behavior of the Java standard library. No benchmarks, test results or destination-specific checks were supplied, so performance figures are not given. Behavior in a particular editor, terminal, browser or assistive technology has not been verified here. Confirm these points with your own JDK version and target environment before relying on them.