Library contents

Java String.replaceAll

Replace every non-overlapping match for a regular expression.

A simple example

String.replaceAll

  1. Start with "a1b2"
  2. Do this Replace each digit with *
  3. Result "a*b*"
The digit pattern finds two matches. Both are replaced.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("a1b2".replaceAll("[0-9]", "*"));
    }
}
Output
a*b*

Syntax

Java syntax
public String replaceAll(String regex, String replacement)
JDK 21 method signatures (1)
public String replaceAll(String regex, String replacement)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Normalize spacing on a shipping label

A printed code uses separators or spacing that are awkward for a reader. Convert the display copy to the desired format and preserve the original value needed by the source system.

From the programString label = "North Gate 2"
ResultNorth Gate 2
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String label = "North   Gate  2";
        System.out.println(label.replaceAll(" +", " "));
    }
}
Output
North Gate 2

Each run of ordinary spaces becomes one space.

Advertisements

Hide each digit on a shared ticket

A service desk displays an identifier where bystanders could see it. Replace the intended numeric field or digit runs while preserving the rest of the record for the operator.

From the programString ticket = "AB-482"
ResultAB-***
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String ticket = "AB-482";
        System.out.println(ticket.replaceAll("[0-9]", "*"));
    }
}
Output
AB-***

Each individual digit matches once and is replaced by an asterisk.

Mask a public job number

A noticeboard shows the department prefix and hides the serial. The editor replaces a matching run of digits with a single star before sharing the label. Each sample has one numeric run.

GivenART-184 → replace digits
Worked resultART-*

What to watch for

Use replace for literal text. Compile a Pattern if the same expression is reused many times.

Documentation for String.replaceAll