Java Matcher replaceAll() Method
Example
Replace all numbers in a sentence with #:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher("The binary representation of 5 is 101.");
System.out.println(matcher.replaceAll("#"));
}
}
Definition and Usage
The replaceAll() method replaces every match of the pattern with a new text, and returns the result as a new string. The original text is not changed.
In the example, [0-9]+ means "one or more digits from 0 to 9", so each number is replaced with #.
Note: The characters $ and \ have a special meaning in the replacement text. For example, $1 inserts the text of group 1. Use Matcher.quoteReplacement() to make them normal characters.
Syntax
public String replaceAll(String replacement)
Parameter Values
| Parameter | Description |
|---|---|
| replacement | Required. The text to put in place of each match. |
Technical Details
| Returns: | A new String where every match is replaced. |
|---|
Related Pages
❮ RegEx Methods