Java String.replaceAll
Replace every non-overlapping match for a regular expression.
A simple example
String.replaceAll
- Start with "a1b2"
- Do this Replace each digit with *
- Result "a*b*"
class Main {
public static void main(String[] args) throws Exception {
System.out.println("a1b2".replaceAll("[0-9]", "*"));
}
}
a*b*
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.javaNormalize 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.
class Main {
public static void main(String[] args) throws Exception {
String label = "North Gate 2";
System.out.println(label.replaceAll(" +", " "));
}
}
North Gate 2
Each run of ordinary spaces becomes one space.
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.
class Main {
public static void main(String[] args) throws Exception {
String ticket = "AB-482";
System.out.println(ticket.replaceAll("[0-9]", "*"));
}
}
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.
What to watch for
Use replace for literal text. Compile a Pattern if the same expression is reused many times.