Java String replaceAll() Method

Intermediate
5 min read
Updated: Nov 2026
3 examples
String

Definition

In Java, replaceAll(regex, replacement) returns a new String in which every part that matches the regular expression regex is replaced. It is equivalent to Pattern.compile(regex).matcher(text).replaceAll(replacement).

Regex makes one call do a lot: "\\s+" matches any run of whitespace, "[^0-9]" any non-digit. In the replacement, $1, $2, ... insert captured groups, so you can reorder parts of the match.

replaceAll() is an instance method of java.lang.String, added in Java 1.4. Call it on a string, as in text.replaceAll(...); calling it on a null reference throws NullPointerException. Strings are immutable, so it never changes the original: it returns a new String (or the same one when nothing changes). Keep the result.

Syntax

Pass a regex and a replacement. Remember that a regex backslash is written twice inside a Java string literal.

java
String tidy   = text.replaceAll("\\s+", " ");
String digits = phone.replaceAll("[^0-9]", "");
String swap   = name.replaceAll("(\\w+) (\\w+)", "$2, $1");
CallWhat it does
"a1b22c".replaceAll("\\d", "#")"a#b##c".
"a1b22c".replaceAll("\\d+", "#")"a#b#c".
"a.b".replaceAll(".", "x")"xxx": . matches any char.

$ and \ are special in the replacement string. To insert text that may contain them (prices, Windows paths), wrap it with Matcher.quoteReplacement(text), or use the literal replace instead.

Library declarations
java
public String replaceAll(String regex, String replacement);

Parameters

ParameterDescription
regexThe regular expression to match.
replacementText for each match; $n inserts group n, \$ inserts a dollar sign.

Return Value

Return ValueDescription
StringThe text with every match replaced.

Java Examples

Example 1 — Collapse Spaces and Keep Only Digits

Two everyday clean-up jobs, each done with one regex.

java
public class ReplaceAllSpaces {
    public static void main(String[] args) {
        String messy = "  too   many    spaces ";
        String tidy = messy.replaceAll("\\s+", " ");
        String digits = "(555) 123-4567".replaceAll("[^0-9]", "");

        System.out.println("[" + tidy + "]");
        System.out.println(digits);
    }
}

How It Works

  1. One space per run. The regex \s+ matches each run of whitespace as a whole, so every gap shrinks to a single space.
  2. Edges are runs too. The leading and trailing runs also become one space; call strip() afterwards if you want them gone.
  3. Delete with an empty replacement. [^0-9] matches every non-digit, and replacing it with "" leaves 5551234567.

Example 2 — Reorder a Date with Group References

Capture the parts of an ISO date and write them back in a different order.

java
public class ReplaceAllGroups {
    public static void main(String[] args) {
        String iso = "2026-11-19";
        String european = iso.replaceAll("(\\d{4})-(\\d{2})-(\\d{2})", "$3/$2/$1");
        String masked = "Card 1234-5678".replaceAll("\\d", "*");

        System.out.println(european);
        System.out.println(masked);
    }
}

How It Works

  1. Three capturing groups. The parentheses capture the year as group 1, the month as group 2, and the day as group 3.
  2. Rebuild in any order. The replacement "$3/$2/$1" writes day, month, and year with slashes, giving 19/11/2026.
  3. Mask characters. The regex \d matches one digit at a time, so each of the eight digits becomes an asterisk while the dash stays.

Example 3 — Insert Text That Contains a Dollar Sign

A price like $9.99 breaks a raw replacement until it is quoted.

java
import java.util.regex.Matcher;

public class ReplaceAllDollar {
    public static void main(String[] args) {
        String template = "Total: PRICE";
        String price = "$9.99";

        try {
            template.replaceAll("PRICE", price);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("raw $9 fails: " + e.getClass().getSimpleName());
        }
        System.out.println(template.replaceAll("PRICE", Matcher.quoteReplacement(price)));
        System.out.println(template.replace("PRICE", price));
    }
}

How It Works

  1. $9 means group 9. In a replacement string, $9 asks for capture group 9; the regex PRICE has no groups, so the call throws.
  2. Quote the replacement. Matcher.quoteReplacement escapes the dollar sign, and the price is inserted unchanged.
  3. Or skip regex entirely. The literal replace method treats $ as an ordinary character and gives the same result.

Frequently Asked Questions

Yes. The first argument is a regex, so characters such as . * + ? ( ) [ ] { } \ ^ $ | have special meanings. Escape them or use replace() for literal text.
Write $1, $2, and so on in the replacement string. For example, the regex (\w+)@(\w+) with the replacement "$2 at $1" swaps the two parts.
In the replacement, $ starts a group reference. Use Matcher.quoteReplacement(text) or write \$ to insert a literal dollar sign.
replace() is literal and replaces all occurrences. replaceAll() also replaces all occurrences but matches a regex and supports group references.
Start the regex with the (?i) flag, for example text.replaceAll("(?i)java", "Java").

Next: replaceFirst()

Replace only the first regex match.

replaceFirst() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful