Java replaceAll Regex: What It Changes, Where It Breaks and When to Use Something Simpler
How Java's String.replaceAll works with regular expressions, how it differs from replace and replaceFirst, how it handles Unicode, and when a plain literal replacement is the safer choice.
What replaceAll does in Java
String.replaceAll(regex, replacement) returns a new string in which every substring matching the regular expression is replaced with the replacement string. The Java documentation defines it as equivalent to Pattern.compile(regex).matcher(str).replaceAll(replacement). Java strings are immutable, so the original string is never modified. If the result is not assigned to a variable, the call has no visible effect, which is a common source of confusion.
String input = "a1b22c333";
String output = input.replaceAll("\\d+", "#");
// input -> "a1b22c333" (unchanged)
// output -> "a#b#c#"
input.replaceAll("\\d+", "#"); // result discarded; input is still "a1b22c333"
How replaceAll differs from replace and replaceFirst
The method names suggest that replace changes one occurrence and replaceAll changes all of them. That is not the distinction. Both replace every occurrence. The difference is that replace treats its arguments as literal text, while replaceAll treats the first argument as a regular expression and the second as a replacement template with its own special characters.
| Method | Pattern interpreted as | Occurrences replaced | Special characters in replacement |
| String.replace(CharSequence, CharSequence) | Literal text | All | None |
| String.replaceAll(String, String) | Regular expression | All | $ and |
| String.replaceFirst(String, String) | Regular expression | First only | $ and |
| Matcher.replaceAll(Function<MatchResult, String>) (Java 9 and later) | Precompiled Pattern | All | None; the function's return value is used literally |
The practical consequence shows up when the search text contains a regex metacharacter such as a period. In a regular expression, an unescaped period matches any character, so every character in the string gets replaced.
"a.b.c".replace(".", "-"); // "a-b-c"
"a.b.c".replaceAll(".", "-"); // "-----" (every character matched)
"a.b.c".replaceAll("\\.", "-"); // "a-b-c"
Two strings, two sets of special characters
The regex argument follows java.util.regex.Pattern syntax, where characters such as . * + ? ( ) [ ] { } | ^ $ and \ have meaning. The replacement argument has separate rules: $ introduces a group reference such as $1 or ${name}, and a backslash escapes the next character. Java string literals add a third layer, because a single regex backslash must be written as two backslashes in source code. When either the pattern or the replacement comes from user input or data, Pattern.quote makes the pattern literal and Matcher.quoteReplacement makes the replacement literal.
String price = "Total: 5";
// Throws IllegalArgumentException: "$" is read as an incomplete group reference
price.replaceAll("\\d+", "$");
// Literal dollar sign in the replacement
price.replaceAll("\\d+", Matcher.quoteReplacement("$5")); // "Total: $5"
// Literal search text that contains metacharacters
"1+1=2".replaceAll(Pattern.quote("1+1"), "two"); // "two=2"
Capturing groups and computed replacements
Groups let the replacement reuse parts of each match, which is how reformatting tasks such as reordering date fields are usually done. Named groups (Java 7 and later) make longer patterns easier to read. When the replacement depends on logic rather than a fixed template, Java 9 added Matcher.replaceAll with a function; its return value is inserted literally, so $ and \ in the computed text need no escaping.
"2026-10-31".replaceAll("(\\d{4})-(\\d{2})-(\\d{2})", "$3/$2/$1");
// "31/10/2026"
"2026-10-31".replaceAll("(?<y>\\d{4})-(?<m>\\d{2})-(?<d>\\d{2})", "${d}.${m}.${y}");
// "31.10.2026"
Pattern word = Pattern.compile("\\b\\w");
word.matcher("hello world").replaceAll(m -> m.group().toUpperCase());
// "Hello World"
What the transformation actually changes
replaceAll changes the stored characters of the resulting string. It does not apply any visual effect: there is no font, styling, CSS presentation or mirrored rendering involved, and the output is ordinary text wherever it is copied. It also does not reverse text. Reordering happens only when a pattern explicitly captures pieces and rearranges them, as in the date example. If a workflow calls for reversed or mirrored text, that comes from separate code or from display settings, not from replaceAll itself.
Unicode: code points, combining marks and emoji
Java regular expressions operate on Unicode code points, so a supplementary character stored as two UTF-16 units is still matched as one unit by a period. A single visible character, however, can consist of several code points: a letter plus a combining accent, or an emoji plus a skin-tone modifier. A pattern that matches one code point at a time can split these apart. Since Java 9, \X matches an extended grapheme cluster, which is closer to what a reader sees as one character. Normalizing text with java.text.Normalizer before matching can also turn a letter-plus-accent sequence into a single precomposed character where one exists.
String thumb = "\uD83D\uDC4D\uD83C\uDFFD"; // thumbs-up + medium skin tone
thumb.replaceAll(".", "x"); // "xx" (two code points)
thumb.replaceAll("\\X", "x"); // "x" (one grapheme cluster, Java 9+)
String decomposed = "e\u0301"; // e + combining acute accent
decomposed.replaceAll("\\P{L}", ""); // "e" (accent removed as a non-letter)
Normalizer.normalize(decomposed, Normalizer.Form.NFC)
.replaceAll("\\P{L}", ""); // "\u00E9" (é is kept)
Character classes have ASCII defaults. Without flags, \w matches only [a-zA-Z_0-9], \s does not include the non-breaking space, and case-insensitive matching applies only to ASCII letters. The (?U) flag (UNICODE_CHARACTER_CLASS) makes the predefined classes Unicode-aware, and (?iu) enables Unicode case folding. Explicit properties such as \p{L} for letters and \p{M} for marks are often clearer than relying on flags.
Readability and usability after copying or sharing
Because the output is plain text, it copies and pastes as exactly the characters it contains. The usability risk lies in what the pattern removed or altered. Common cleanup patterns can damage text in ways that are easy to miss in testing with English-only samples:
- Stripping everything outside [a-zA-Z0-9] deletes accented letters and entire non-Latin scripts, which harms readability and makes the text harder to find by search.
- Removing format characters (\p{Cf}) also removes zero-width joiners, which can split a combined emoji into its separate parts.
- The same \p{Cf} removal deletes bidirectional control characters, which can change the displayed order of mixed right-to-left and left-to-right text.
- Collapsing whitespace with \s+ under default settings leaves non-breaking spaces untouched, so text can look cleaned while still containing irregular spacing.
- Replacing punctuation can change how assistive technology reads the text, since screen readers announce the characters that remain; behavior varies by reader and settings and should be checked in the target environment.
Keep the original string whenever the transformed version is lossy, for example when producing a search key or slug. Display and accessibility should use the original or a deliberately normalized plain-text version, and the transformed value should be treated as derived data.
Errors and performance
An invalid pattern throws PatternSyntaxException at run time. In the replacement string, a reference to a numbered group that does not exist throws IndexOutOfBoundsException, and a malformed or unknown named reference throws IllegalArgumentException. Because String.replaceAll compiles its pattern on every call, code that applies the same pattern repeatedly, such as inside a loop, typically compiles a Pattern once and reuses it with matcher(...).replaceAll(...). No benchmark measurements were supplied, so the size of that difference in a given workload should be measured rather than assumed.
Is replaceAll the right tool?
replaceAll is a good fit when the text to find is described by a pattern, such as runs of digits, repeated whitespace, or structured fields to reorder. Its main benefit is expressing a whole class of matches in one call. Its decisive tradeoff is that both arguments are interpreted, so literal text containing a period, dollar sign or backslash can silently produce wrong output or throw an exception. Plain replace is preferable in these cases:
- The search text is a fixed literal string.
- The search or replacement text comes from users, configuration or other data you do not control.
- The pattern is hot-path code that would benefit from a precompiled Pattern.
- The input may contain non-ASCII text, and the pattern has only been tested with ASCII samples. In this case, use Unicode-aware classes or flags and keep the original text.
Evidence gaps
This overview is based on documented Java behavior and general Unicode principles. No subject-specific test results, performance figures, or assistive-technology test results were supplied. Claims about how particular screen readers, platforms or destinations handle transformed text have not been verified here and should be confirmed with scoped tests in the environment where the text will be used.