Editor's note (2026): The original 2014 version of this post reproduced a tutorial from Java Code Geeks. We've replaced it with our own examples and added an important tip:
replaceAll()treats its first argument as a regular expression.
Java's String.replaceAll(regex, replacement) returns a new string with every match of a pattern replaced. Because Java strings are immutable, the original string never changes; you get a new one back.
Replacing single characters
public class ReplaceAllDemo {
public static void main(String[] args) {
String str = "This is a String to use as an example";
System.out.println(str.replaceAll("a", "@"));
// This is @ String to use @s @n ex@mple
System.out.println(str.replaceAll("e", "3"));
// This is a String to us3 as an 3xampl3
System.out.println(str.replaceAll("o", ""));
// This is a String t use as an example
}
}
Replacement is case-sensitive: replacing "t" doesn't change "T". Replacing with an empty string removes the character.
Replacing words
String str = "This is a String to use as an example";
System.out.println(str.replaceAll("This", "That"));
// That is a String to use as an example
System.out.println(str.replaceAll("String", "big String"));
// This is a big String to use as an example
System.out.println(str.replaceAll("is", ""));
// Th a String to use as an example
Notice that removing "is" also changed "This" to "Th". To match whole words only, use word boundaries: str.replaceAll("\\bis\\b", "").
Using regular expressions
This is where replaceAll() shines:
String str = "This 1231 is 124 a String 1243 to 34563 use 5455";
// Remove all numbers
System.out.println(str.replaceAll("[0-9]+", ""));
// "This is a String to use "
// Replace every word with "Java"
System.out.println(str.replaceAll("[a-zA-Z]+", "Java"));
// "Java 1231 Java 124 Java Java 1243 Java 34563 Java 5455"
// Collapse multiple spaces into one
System.out.println(str.replaceAll("\\s+", " "));
replace() vs. replaceAll()
replace(target, replacement)replaces literal text. Use it when you don't need patterns.replaceAll(regex, replacement)treats the first argument as a regular expression. Characters like.,$,*,(, and\have special meanings, so"1.5".replaceAll(".", "-")returns"---", not"1-5". UsePattern.quote()orreplace()for literal text.replaceFirst(regex, replacement)replaces only the first match.
Need help with Java or custom software development? I.T. For Less can help — contact us.