Java String replaceAll: Regex Replacement and Pitfalls
Learn how to use Java's String.replaceAll() for regex-based replacement, including escaping, performance, and common mistakes.

When you need to replace every occurrence of a pattern in a Java string, the String.replaceAll() method is the standard tool. Its first argument is a regular expression, which makes it powerful but also easy to misuse. This article explains how replaceAll() behaves, how to handle special characters, and where performance and correctness issues commonly appear.
How replaceAll Works with Regular Expressions
The replaceAll method is defined on String and takes two arguments: a regex pattern and a replacement string. It returns a new string where every non-overlapping match of the pattern is replaced by the replacement. The original string is unchanged because strings are immutable.
String text = "The quick brown fox jumps over the lazy dog.";
String result = text.replaceAll("o", "0");
System.out.println(result);
// The quick br0wn f0x jumps 0ver the lazy d0g.The replacement string is processed by Matcher.replaceAll(), which means that backslashes and dollar signs have special meaning. A $ followed by a group number inserts the captured group, and \ is used to escape characters. For example, to replace with a literal dollar sign, you need to escape it.
Escaping Special Characters in the Replacement String
If the replacement text comes from user input or a configuration value, it may contain characters that the regex replacement engine interprets. For example, a replacement like $1 would be treated as a backreference, not as the literal characters $1. To insert a literal replacement string, use Matcher.quoteReplacement():
String replacement = "$1";
String escaped = java.util.regex.Matcher.quoteReplacement(replacement);
String result = "abc".replaceAll("b", escaped);
System.out.println(result); // a$1cSimilarly, the regex pattern itself must be escaped if you want to match literal characters that are regex metacharacters. For instance, to replace a literal dot, use the character class [.] in the pattern.
ReplaceAll vs Replace
Java's String class also provides replace(CharSequence, CharSequence) which treats both arguments literally. If you do not need regex, replace is simpler and often faster because it does not compile a pattern. For example:
String text = "file.name.txt";
String withReplace = text.replace(".", "-"); // file-name-txt
String withReplaceAll = text.replaceAll("[.]", "-"); // file-name-txtThe replace method replaces all occurrences, just like replaceAll, but without regex semantics. Use replace when you are matching a fixed string. Use replaceAll when the search term is a pattern, or when you need to use backreferences in the replacement.
Performance Considerations
Each call to replaceAll compiles the regular expression from the pattern string. If you call it repeatedly with the same pattern, the compilation overhead is repeated. For high-frequency operations, precompile the pattern using Pattern.compile() and then use a Matcher directly:
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(input);
String result = matcher.replaceAll("#");This is especially important in loops or in server-side request handling where the same pattern is applied to many strings. The compiled Pattern is immutable and thread-safe, so it can be shared across threads. The Matcher itself is not thread-safe, but you can create one per call.
Another detail: replaceAll creates a new string and may allocate temporary buffers. If you are doing many replacements, Matcher.appendReplacement() and appendTail() let you build the result incrementally and give you more control over each replacement.
Common Pitfalls with Regex Patterns
A frequent mistake is forgetting that the first argument is a regex. For example, text.replaceAll("$", "x") will add x at the end of the string, not replace dollar signs, because $ is the end-of-line anchor. To match a literal dollar sign, use the character class [$].
Another pitfall is using replaceAll with an empty pattern. An empty pattern matches at every position, so the replacement will be inserted between every character. This is rarely what you want.
Also, be careful with replacement strings that contain backslashes. In a Java string literal, \\ represents a single backslash. The replacement engine also treats a backslash as an escape, so producing a literal backslash in the result requires extra escaping in the Java source.
Using Pattern and Matcher for Complex Replacements
For replacements that depend on the matched text, you can use Matcher.appendReplacement() and appendTail() to build the result incrementally. This is useful when the replacement is not a fixed string but is computed from the match.
Pattern pattern = Pattern.compile("\\b(\\w+)\\b");
Matcher matcher = pattern.matcher(input);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String word = matcher.group(1);
matcher.appendReplacement(sb, word.toUpperCase());
}
matcher.appendTail(sb);
String result = sb.toString();Here, each word is converted to uppercase. This approach gives you full control over the replacement logic and avoids the overhead of repeated replaceAll calls when the replacement depends on the match.
Handling Null and Empty Inputs
replaceAll throws NullPointerException if either the regex or the replacement is null. An empty regex string is valid but matches at every position, which can lead to unexpected results. If you are processing user-provided patterns, validate them first or catch PatternSyntaxException for invalid regex syntax.
try {
String result = input.replaceAll(userPattern, replacement);
} catch (java.util.regex.PatternSyntaxException e) {
// handle invalid pattern
}It is also worth noting that replaceAll operates on the entire string and returns a new string. For very large strings, this can consume memory. If you need to process very large text under memory constraints, plan a chunked or streaming approach instead of assuming replaceAll can handle everything in memory.
Compatibility and Java Versions
The replaceAll method has been part of the Java standard library since Java 1.4. Its behavior is consistent across modern Java versions. However, the implementation details of regex matching may vary slightly between releases, but the public API contract is stable. If you are working with Java 9 or later, the underlying String implementation may use compact strings, but that does not change the behavior of replaceAll.
When you need to replace text in a Java string, replaceAll is the right tool when you need regex power. For fixed literals, replace is simpler. For repeated use, precompile the pattern. And for complex replacements, use Matcher methods. Understanding the regex semantics and escaping rules will prevent the most common bugs.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.