The replaceAll(String) method of the Matcher class is used to replace every substring that matches a regular expression with a specified replacement string. It scans the entire input sequence and returns a new string containing all the replacements.
- Uses the regular expression associated with the Matcher object.
- Supports capturing groups ($1, $2, etc.) in the replacement string.
- Commonly used for text formatting, filtering, and data cleaning.
Example: Replacing All Occurrences of a Word
import java.util.regex.*;
public class Geeks {
public static void main(String[] args) {
// Input string
String text = "Java is easy. Java is powerful.";
// Create pattern and matcher
Pattern pattern = Pattern.compile("Java");
Matcher matcher = pattern.matcher(text);
System.out.println("Before Replacement: " + text);
// Replace all occurrences
String result = matcher.replaceAll("Python");
System.out.println("After Replacement: " + result);
}
}
Output
Before Replacement: Java is easy. Java is powerful. After Replacement: Python is easy. Python is powerful.
Explanation: The regular expression matches every occurrence of "Java" in the input string. The replaceAll() method replaces each match with "Python" and returns the updated string.
Syntax
public String replaceAll(String replacement)
- Parameters: The string that replaces every substring matching the regular expression.
- Return Value: Returns a new String in which all matches are replaced with the specified replacement string.
Example: Replacing All Digits
import java.util.regex.*;
public class Geeks {
public static void main(String[] args) {
// Input string
String text = "Order123 will arrive on 25-07-2026.";
// Create pattern and matcher
Pattern pattern = Pattern.compile("\\d");
Matcher matcher = pattern.matcher(text);
System.out.println("Before Replacement: " + text);
// Replace all digits
String result = matcher.replaceAll("#");
System.out.println("After Replacement: " + result);
}
}
Output
Before Replacement: Order123 will arrive on 25-07-2026. After Replacement: Order### will arrive on ##-##-####.
Explanation: The regular expression \\d matches every digit in the input string. The replaceAll() method replaces each digit with #, producing a new string while leaving the original string unchanged.
Advantages of replaceAll(String) Method
- Replaces all matching substrings in a single method call.
- Returns a new string without changing the original string.
- Supports powerful regular expressions for complex replacements.
- Useful for text formatting, data masking, and input sanitization.
- Simplifies bulk text replacement operations using the Matcher class.