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 String is immutable, so no method can change one in place. Every replace method scans the string, copies the unchanged parts and the replacements into a new character array, and returns a new String. When there is nothing to replace, replace returns the original object, so no copy is made.

The methods fall into two groups that look alike but read their arguments differently:

  • replace 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.
  • replaceAll and replaceFirst compile their first argument as a regular expression, and read the second as a template in which $1 means "group 1" and a backslash escapes the next character.
Replace methods in the JDK
MethodSinceSearch isBest for
String.replace(char, char)Java 1.0One characterSwapping one character for another, such as / for \
String.replace(CharSequence, CharSequence)Java 5Literal textMost everyday replacements
String.replaceAll(regex, template)Java 1.4Regular expressionPatterns, groups, reformatting
String.replaceFirst(regex, template)Java 1.4Regular expressionOnly the first match
Matcher.replaceAll(Function)Java 9Compiled PatternReplacements computed from each match
Matcher.appendReplacement and appendTailJava 1.4Compiled PatternFull control of the loop, on any version
StringBuilder.replace(start, end, str)Java 1.0A position rangeEditing 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.

Java
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:

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-
  • replace('/', '\\') changed all four slashes, and replace("ann", "bob") changed the name. Both replace every occurrence.
  • The true line shows that when # is not found, replace returns the very same object. Code that checks result == original can rely on this to know nothing changed, though equals is the safer test.
  • replaceAll(".", "_") turned all 31 characters into underscores, because in a regex . means "any character". replace(".", "_") and the escaped regex "\\." both changed only the two real dots.
  • replaceFirst("/", " -> ") changed only the first slash. There is no literal replaceFirst; for plain text with special characters, quote it with Pattern.quote, shown below.
  • Matching moves left to right and continues after each replacement, so matches never overlap. "aaaa" has two non-overlapping "aa" and becomes bb; "aaa" has one, leaving ba.
  • An empty target matches at every position, including the start and end, so "abc".replace("", "-") gives -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.

Java
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:

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, $2 and $3 insert them. Both 555-123-4567 and 555.987.6543 came out as (555) ..., because [-.] accepts either separator.
  • Named groups, written (?<y>...) and used as ${y} (since Java 7), turned both ISO dates into day/month/year without counting parentheses.
  • $0 is the whole match, so 42 became [42].
  • \1 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.
  • \d(?=\d{4}) uses a lookahead, which checks what follows without consuming it. Each digit with four more digits after it became *, leaving the last four visible.
  • (?i) makes the match case-insensitive. Without (?m), ^ matches only at the start of the whole string, so only the first line got #; with it, every line did.

The regular expressions page covers the pattern syntax in depth.

Special characters: escaping $ and backslash

The replacement argument of replaceAll is a template, not plain text, which breaks as soon as the text contains a dollar sign or a backslash. Prices and Windows paths are the inputs that hit this most often in real code.

Java
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:

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 '+'
  • "$9.99" was read as a reference to group 9, which does not exist, so it threw IndexOutOfBoundsException. A $ at the end, as in "US$", throws IllegalArgumentException instead.
  • Matcher.quoteReplacement escapes $ and \ so the text is inserted as it is. When no regex is needed at all, replace is simpler and gives the same result.
  • The path C:\temp\new silently lost its backslashes and became C:tempnew, because each backslash escaped the letter after it. No exception warns you about this one.
  • In the search, + means "one or more", so the pattern a+b matched aab and not the text a+b. Pattern.quote wraps the text in \Q...\E, which makes the regex engine treat it literally.
  • A lone "+" is not a valid regex, so replaceAll("+", ...) throws PatternSyntaxException with "Dangling meta character".

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.

Java
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:

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
  • Matcher.replaceAll(Function<MatchResult, String>), 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 (\p{Ll}) of each word.
  • The placeholder version fills ${name} and ${total} and leaves ${ref} as it is, because getOrDefault returns the match itself for unknown names.
  • The appendReplacement loop gives the same text and lets the code keep state, here counting 2 of 3 placeholders replaced. It worked only with StringBuffer until Java 9 added StringBuilder overloads.
  • The last line is the trap: the string the function returns is still a template. The value $42.00 was read as group 4, so without quoteReplacement it threw.

Several replacements at once

Chaining replace calls is fine when the replacements cannot interfere with each other. The inputs here are chosen so that they do: a swap, keys where one is the prefix of another, and HTML escaping, where one replacement produces text that another one matches.

Java
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("<", "&lt;").replace("&", "&amp;");
        String right = raw.replace("&", "&amp;").replace("<", "&lt;");
        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:

Output
chained swap:     cat chases cat
one-pass swap:    dog chases cat
prefix keys:      JS and J
& last (wrong):   a &amp;lt; b &amp; c
& first (right):  a &lt; b &amp; c
by position:      4111********4444
  • Swapping by chaining failed: cat became dog, and then the second call turned both dogs into cat, giving cat chases cat.
  • The one-pass helper builds a single regex of all keys, \Qdog\E|\Qcat\E, and looks up each match in the map. Each part of the text is replaced at most once, so the swap worked.
  • Regex alternation tries the alternatives in order, so the helper sorts keys longest first. Otherwise Java would match the start of JavaScript and give JScript.
  • In HTML escaping, replacing < first produces &lt;, 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.
  • StringBuilder.replace(4, 12, ...) replaced characters 4 to 11 by position, which no search-based method can do directly.

For other ways to edit text in place, see StringBuilder.

How fast is each approach?

The program replaces ERROR with WARN in 1,000,000 short log lines, a third of which contain it. Each approach runs 3 times and the best run is reported.

Java
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):

Output
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
  • String.replace searches with indexOf 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.
  • String.replaceAll was about eight times slower than replace for the same literal search, because it compiles a new Pattern on every call. Using it for plain text is the most common replacement performance mistake.
  • A Pattern compiled once and stored in a static final field removes the compile cost, but running the regex engine still made it two to three times slower than replace.
  • The hand-written indexOf loop was 15 to 40 percent faster than replace 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.

Which method to use

Choosing a replace method
SituationUse
Replace plain text everywheres.replace(target, replacement)
Replace one character with anothers.replace('a', 'b')
Match a pattern or reorder partss.replaceAll(regex, "$1...")
Only the first matchs.replaceFirst(regex, template)
Replacement text from data or user inputMatcher.quoteReplacement(text), or plain replace
Search text from data or user inputPattern.quote(text)
Replacement computed from the matchpattern.matcher(s).replaceAll(m -> ...) (Java 9)
Same regex used many timesA static final Pattern
Several keys that may interfereOne pass with an alternation of quoted keys, longest first
Change a known positionStringBuilder.replace(start, end, str)

To remove whitespace specifically, see removing whitespace; to find where text occurs before replacing it, see indexOf.