Replace Text in a String
Java has two families of replace methods: replace treats its arguments as plain text, while replaceAll and replaceFirst treat them as a regular expression and a replacement template. Mixing them up causes most replacement bugs. This page explains how each works, shows regex groups, escaping, computed replacements and multi-key replacement, and measures what each costs.
Contents
How replacing text works in Java
A StringStringreplace
The methods fall into two groups that look alike but read their arguments differently:
works with plain text. A dot is a dot and a dollar sign is a dollar sign. Despite its name, it replaces every occurrence, not just the first. Since Java 9 it no longer uses the regex engine internally (JDK-8058779), which made it much faster.replace andreplaceAll compile their first argument as a regular expression, and read the second as a template in whichreplaceFirst means "group 1" and a backslash escapes the next character.$1
| Method | Since | Search is | Best for |
|---|---|---|---|
String.replace(char, char) | Java 1.0 | One character | Swapping one character for another, such as /\ |
String.replace(CharSequence, CharSequence) | Java 5 | Literal text | Most everyday replacements |
String.replaceAll(regex, template) | Java 1.4 | Regular expression | Patterns, groups, reformatting |
String.replaceFirst(regex, template) | Java 1.4 | Regular expression | Only the first match |
Matcher.replaceAll(Function) | Java 9 | Compiled Pattern | Replacements computed from each match |
Matcher.appendReplacementappendTail | Java 1.4 | Compiled Pattern | Full control of the loop, on any version |
StringBuilder.replace(start, end, str) | Java 1.0 | A position range | Editing a known region in place |
All programs on this page are complete classes, compiled and run on JDK 21.
Literal replacement and the dot trap
A Windows-style path is a good test input, because it contains slashes, a name to swap and dots, and the dot is exactly the character that behaves differently in the two method families.
public class ReplaceBasics {
public static void main(String[] args) {
String path = "C:/users/ann/docs/report.v1.txt";
System.out.println(path.replace('/', '\\')); // every char
System.out.println(path.replace("ann", "bob")); // every literal substring
System.out.println(path.replace('#', '_') == path); // char not found: same object back
// The dot trap: replaceAll treats its first argument as a regex
System.out.println("replace(\".\", \"_\"): " + path.replace(".", "_"));
System.out.println("replaceAll(\".\", \"_\"): " + path.replaceAll(".", "_"));
System.out.println("replaceAll(\"\\\\.\", \"_\"): " + path.replaceAll("\\.", "_"));
System.out.println("replaceFirst: " + path.replaceFirst("/", " -> "));
// Overlapping matches: scanning continues after each replacement
System.out.println("\"aaaa\".replace(\"aa\", \"b\") = " + "aaaa".replace("aa", "b"));
System.out.println("\"aaa\".replace(\"aa\", \"b\") = " + "aaa".replace("aa", "b"));
// An empty target matches between every pair of characters
System.out.println("\"abc\".replace(\"\", \"-\") = " + "abc".replace("", "-"));
}
}
Output:
C:\users\ann\docs\report.v1.txt
C:/users/bob/docs/report.v1.txt
true
replace(".", "_"): C:/users/ann/docs/report_v1_txt
replaceAll(".", "_"): _______________________________
replaceAll("\\.", "_"): C:/users/ann/docs/report_v1_txt
replaceFirst: C: -> users/ann/docs/report.v1.txt
"aaaa".replace("aa", "b") = bb
"aaa".replace("aa", "b") = ba
"abc".replace("", "-") = -a-b-c-
changed all four slashes, andreplace('/', '\\') changed the name. Both replace every occurrence.replace("ann", "bob")- The
line shows that whentrue is not found,# returns the very same object. Code that checksreplace can rely on this to know nothing changed, thoughresult == original is the safer test.equals turned all 31 characters into underscores, because in a regexreplaceAll(".", "_") means "any character".. and the escaped regexreplace(".", "_") both changed only the two real dots."\\." changed only the first slash. There is no literalreplaceFirst("/", " -> ") ; for plain text with special characters, quote it withreplaceFirst , shown below.Pattern.quote- Matching moves left to right and continues after each replacement, so matches never overlap.
has two non-overlapping"aaaa" and becomes"aa" ;bb has one, leaving"aaa" .ba - An empty target matches at every position, including the start and end, so
gives"abc".replace("", "-") .-a-b-c-
Regex replacement: groups, named groups and lookahead
Regex replacement can reorder parts of the text, not just swap it. The inputs are values whose format often needs changing: phone numbers in two styles, ISO dates, doubled words and a card number.
public class RegexGroups {
public static void main(String[] args) {
String phone = "Call 555-123-4567 or 555.987.6543";
// Groups captured with ( ) are reused as $1, $2 ... in the replacement
System.out.println(phone.replaceAll("(\\d{3})[-.](\\d{3})[-.](\\d{4})", "($1) $2-$3"));
// Named groups are clearer when there are many: ${name}
String date = "Due 2026-11-14, paid 2026-12-01";
String regex = "(?<y>\\d{4})-(?<m>\\d{2})-(?<d>\\d{2})";
System.out.println(date.replaceAll(regex, "${d}/${m}/${y}"));
// $0 is the whole match
System.out.println("error at line 42".replaceAll("\\d+", "[$0]"));
// A back-reference in the pattern: remove doubled words
System.out.println("this is is a test test".replaceAll("\\b(\\w+) \\1\\b", "$1"));
// Lookahead: mask every digit that still has 4 digits after it
System.out.println("4111222233334444".replaceAll("\\d(?=\\d{4})", "*"));
// Case-insensitive match, and only the first one
System.out.println("Java JAVA java".replaceAll("(?i)java", "Kotlin"));
System.out.println("Java JAVA java".replaceFirst("(?i)JAVA", "Kotlin"));
// ^ and $ match per line only with (?m)
String text = "a=1\nb=2";
System.out.println(text.replaceAll("^", "# ").replace("\n", " | "));
System.out.println(text.replaceAll("(?m)^", "# ").replace("\n", " | "));
}
}
Output:
Call (555) 123-4567 or (555) 987-6543
Due 14/11/2026, paid 01/12/2026
error at line [42]
this is a test
************4444
Kotlin Kotlin Kotlin
Kotlin JAVA java
# a=1 | b=2
# a=1 | # b=2
- Parentheses capture parts of the match, and
,$1 and$2 insert them. Both$3 and555-123-4567 came out as555.987.6543 , because(555) ... accepts either separator.[-.] - Named groups, written
and used as(?<y>...) (since Java 7), turned both ISO dates into day/month/year without counting parentheses.${y} is the whole match, so$0 became42 .[42] inside the pattern is a back-reference: it matches the same text that group 1 matched, which finds the two words written twice in a row and keeps one copy of each.\1 uses a lookahead, which checks what follows without consuming it. Each digit with four more digits after it became\d(?=\d{4}) , leaving the last four visible.* makes the match case-insensitive. Without(?i) ,(?m) matches only at the start of the whole string, so only the first line got^ ; with it, every line did.#
The
Special characters: escaping $ and backslash
The replacement argument of replaceAll
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EscapingTraps {
public static void main(String[] args) {
String template = "Total: AMOUNT";
// $ in the replacement means "group reference"
try {
System.out.println(template.replaceAll("AMOUNT", "$9.99"));
} catch (IndexOutOfBoundsException e) {
System.out.println("replaceAll with \"$9.99\": " + e.getClass().getSimpleName()
+ ": " + e.getMessage());
}
try {
System.out.println(template.replaceAll("AMOUNT", "US$"));
} catch (IllegalArgumentException e) {
System.out.println("replaceAll with \"US$\": " + e.getMessage());
}
System.out.println(template.replaceAll("AMOUNT", Matcher.quoteReplacement("$9.99")));
System.out.println(template.replace("AMOUNT", "$9.99"));
// \ in the replacement escapes the next character, so it disappears
String dir = "C:\\temp\\new";
System.out.println("replaceAll: " + "save to DIR".replaceAll("DIR", dir));
System.out.println("quoted: "
+ "save to DIR".replaceAll("DIR", Matcher.quoteReplacement(dir)));
// Special characters in the search text
String userInput = "a+b";
System.out.println("unquoted: " + "x a+b y aab".replaceAll(userInput, "SUM"));
String quoted = Pattern.quote(userInput);
System.out.println("quoted: " + "x a+b y aab".replaceAll(quoted, "SUM"));
System.out.println("Pattern.quote(\"a+b\") = " + Pattern.quote(userInput));
try {
System.out.println("1+1=2".replaceAll("+", "plus"));
} catch (java.util.regex.PatternSyntaxException e) {
System.out.println("replaceAll(\"+\"): " + e.getDescription());
}
}
}
Output:
replaceAll with "$9.99": IndexOutOfBoundsException: No group 9
replaceAll with "US$": Illegal group reference: group index is missing
Total: $9.99
Total: $9.99
replaceAll: save to C:tempnew
quoted: save to C:\temp\new
unquoted: x a+b y SUM
quoted: x SUM y aab
Pattern.quote("a+b") = \Qa+b\E
replaceAll("+"): Dangling meta character '+'
was read as a reference to group 9, which does not exist, so it threw"$9.99" . AIndexOutOfBoundsException at the end, as in$ , throws"US$" instead.IllegalArgumentException escapesMatcher.quoteReplacement and$ so the text is inserted as it is. When no regex is needed at all,\ is simpler and gives the same result.replace- The path
silently lost its backslashes and becameC:\temp\new , because each backslash escaped the letter after it. No exception warns you about this one.C:tempnew - In the search,
means "one or more", so the pattern+ matcheda+b and not the textaab .a+b wraps the text inPattern.quote , which makes the regex engine treat it literally.\Q...\E - A lone
is not a valid regex, so"+" throwsreplaceAll("+", ...) with "Dangling meta character".PatternSyntaxException
Rule of thumb: whenever any part of a regex or a replacement comes from data or user input, quote it.
Computed replacements with Matcher
Sometimes each replacement depends on what was matched, such as a number to transform or a placeholder to look up. The template here has two known placeholders and one unknown, and one value contains a dollar sign, to show the quoting rule still applies.
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ComputedReplace {
static final Pattern NUMBER = Pattern.compile("\\d+");
static final Pattern PLACEHOLDER = Pattern.compile("\\$\\{(\\w+)}");
public static void main(String[] args) {
// Java 9+: a function computes each replacement from the match
String doubled = NUMBER.matcher("3 apples and 12 pears")
.replaceAll(m -> String.valueOf(Integer.parseInt(m.group()) * 2));
System.out.println(doubled);
// Capitalize the first letter of each word
String title = Pattern.compile("\\b\\p{Ll}").matcher("the quick brown fox")
.replaceAll(m -> m.group().toUpperCase());
System.out.println(title);
// Fill placeholders from a map; unknown names stay as they are
Map<String, String> values = Map.of("name", "Ada", "total", "$42.00");
String template = "Dear ${name}, you owe ${total}. Ref: ${ref}";
String filled = PLACEHOLDER.matcher(template).replaceAll(m -> Matcher.quoteReplacement(
values.getOrDefault(m.group(1), m.group())));
System.out.println(filled);
// The same with appendReplacement/appendTail, which works on every Java version
Matcher m = PLACEHOLDER.matcher(template);
StringBuilder sb = new StringBuilder();
int replaced = 0;
while (m.find()) {
String value = values.get(m.group(1));
if (value != null) {
replaced++;
}
m.appendReplacement(sb, Matcher.quoteReplacement(value != null ? value : m.group()));
}
m.appendTail(sb);
System.out.println(sb + " (" + replaced + " of 3 replaced)");
// The function result is itself a replacement string: an unquoted $ fails
try {
PLACEHOLDER.matcher(template).replaceAll(r -> values.getOrDefault(r.group(1), "?"));
} catch (IndexOutOfBoundsException e) {
System.out.println("without quoteReplacement: " + e.getMessage());
}
}
}
Output:
6 apples and 24 pears
The Quick Brown Fox
Dear Ada, you owe $42.00. Ref: ${ref}
Dear Ada, you owe $42.00. Ref: ${ref} (2 of 3 replaced)
without quoteReplacement: No group 4
, added in Java 9, calls the function for each match. It doubled 3 and 12 to 6 and 24, and capitalized the first lowercase letter (Matcher.replaceAll(Function<MatchResult, String>) ) of each word.\p{Ll}- The placeholder version fills
and${name} and leaves${total} as it is, because${ref} returns the match itself for unknown names.getOrDefault - The
loop gives the same text and lets the code keep state, here counting 2 of 3 placeholders replaced. It worked only withappendReplacement until Java 9 addedStringBuffer overloads.StringBuilder - The last line is the trap: the string the function returns is still a template. The value
was read as group 4, so without$42.00 it threw.quoteReplacement
Several replacements at once
Chaining replace
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class MultiReplace {
public static void main(String[] args) {
// Chained replace: the second call also changes what the first call produced
String s = "cat chases dog";
String chained = s.replace("cat", "dog").replace("dog", "cat");
System.out.println("chained swap: " + chained);
// One pass: each match is looked up once, so replacements are never replaced again
Map<String, String> swap = Map.of("cat", "dog", "dog", "cat");
System.out.println("one-pass swap: " + replaceAll(s, swap));
// Longer keys must win over their prefixes: "Java" vs "JavaScript"
Map<String, String> langs = Map.of("Java", "J", "JavaScript", "JS");
System.out.println("prefix keys: " + replaceAll("JavaScript and Java", langs));
// HTML escaping: & must be handled first when chaining
String raw = "a < b & c";
String wrong = raw.replace("<", "<").replace("&", "&");
String right = raw.replace("&", "&").replace("<", "<");
System.out.println("& last (wrong): " + wrong);
System.out.println("& first (right): " + right);
// Replace by position with StringBuilder, editing in place
StringBuilder card = new StringBuilder("4111222233334444");
card.replace(4, 12, "********");
System.out.println("by position: " + card);
}
// Builds one alternation of all keys, longest first, and replaces in a single pass
static String replaceAll(String text, Map<String, String> map) {
String alternation = map.keySet().stream()
.sorted((a, b) -> b.length() - a.length())
.map(Pattern::quote)
.collect(Collectors.joining("|"));
return Pattern.compile(alternation).matcher(text).replaceAll(m ->
java.util.regex.Matcher.quoteReplacement(map.get(m.group())));
}
}
Output:
chained swap: cat chases cat
one-pass swap: dog chases cat
prefix keys: JS and J
& last (wrong): a &lt; b & c
& first (right): a < b & c
by position: 4111********4444
- Swapping by chaining failed:
becamecat , and then the second call turned both dogs intodog , givingcat .cat chases cat - The one-pass helper builds a single regex of all keys,
, and looks up each match in the map. Each part of the text is replaced at most once, so the swap worked.\Qdog\E|\Qcat\E - Regex alternation tries the alternatives in order, so the helper sorts keys longest first. Otherwise
would match the start ofJava and giveJavaScript .JScript - In HTML escaping, replacing
first produces< , whose< the next call then escapes again. Replacing& first gives the right result. When order matters like this, a one-pass replacement removes the problem.& replaced characters 4 to 11 by position, which no search-based method can do directly.StringBuilder.replace(4, 12, ...)
For other ways to edit text in place, see
How fast is each approach?
The program replaces ERRORWARN
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
public class ReplaceSpeed {
static final Pattern LITERAL = Pattern.compile("ERROR", Pattern.LITERAL);
public static void main(String[] args) {
String[] lines = new String[1000000];
for (int i = 0; i < lines.length; i++) {
String level = i % 3 == 0 ? "ERROR" : "INFO";
lines[i] = level + " request " + i + " took " + (i % 97) + "ms";
}
System.out.printf("%,d short lines%n", lines.length);
time("String.replace", lines, s -> s.replace("ERROR", "WARN"));
time("String.replaceAll", lines, s -> s.replaceAll("ERROR", "WARN"));
time("precompiled Pattern", lines, s -> LITERAL.matcher(s).replaceAll("WARN"));
time("indexOf + StringBuilder", lines, ReplaceSpeed::manual);
}
static String manual(String s) {
int at = s.indexOf("ERROR");
if (at < 0) {
return s;
}
StringBuilder sb = new StringBuilder(s.length());
int from = 0;
while (at >= 0) {
sb.append(s, from, at).append("WARN");
from = at + 5;
at = s.indexOf("ERROR", from);
}
return sb.append(s, from, s.length()).toString();
}
// Best of 3 runs, so the JIT warm-up in the first run is not what is measured
static void time(String name, String[] lines, UnaryOperator<String> f) {
long best = Long.MAX_VALUE;
int changed = 0;
for (int run = 0; run < 3; run++) {
changed = 0;
long t0 = System.nanoTime();
for (String line : lines) {
if (f.apply(line) != line) {
changed++;
}
}
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf("%-24s %6.1f ms %,d new strings%n", name, best / 1e6, changed);
}
}
Output (rough comparison on a 2-CPU Linux machine, JDK 21; times differ on other machines):
1,000,000 short lines
String.replace 28.3 ms 333,334 new strings
String.replaceAll 217.4 ms 333,334 new strings
precompiled Pattern 75.3 ms 333,334 new strings
indexOf + StringBuilder 24.4 ms 333,334 new strings
searches withString.replace and returns the original line for the two thirds that contain no match, which is why 333,334 new strings were created, not 1,000,000.indexOf was about eight times slower thanString.replaceAll for the same literal search, because it compiles a newreplace on every call. Using it for plain text is the most common replacement performance mistake.Pattern- A
compiled once and stored in aPattern field removes the compile cost, but running the regex engine still made it two to three times slower thanstatic final .replace - The hand-written
loop was 15 to 40 percent faster thanindexOf across several runs, because it knows the target length in advance and handles one fixed target. That is rarely worth the extra code outside a measured hot spot.replace
Which method to use
| Situation | Use |
|---|---|
| Replace plain text everywhere | s.replace(target, replacement) |
| Replace one character with another | s.replace('a', 'b') |
| Match a pattern or reorder parts | s.replaceAll(regex, "$1...") |
| Only the first match | s.replaceFirst(regex, template) |
| Replacement text from data or user input | Matcher.quoteReplacement(text)replace |
| Search text from data or user input | Pattern.quote(text) |
| Replacement computed from the match | pattern.matcher(s).replaceAll(m -> ...) |
| Same regex used many times | A static final Pattern |
| Several keys that may interfere | One pass with an alternation of quoted keys, longest first |
| Change a known position | StringBuilder.replace(start, end, str) |
To remove whitespace specifically, see