Java String replaceAll() Method
Example
Replace every match of a regular expression with a substring:
String myStr = "I love cats. Cats are very easy to love. Cats are very popular.";
String regex = "(?i)cat";
System.out.println(myStr.replaceAll(regex, "dog"));
Definition and Usage
The replaceAll()
method replaces the first match of a regular expression in a string with a new substring.
Replacement strings may contain a backreference in the form $n where n is the index of a group in the pattern. In the returned string, instances of $n will be replaced with the substring that was matched by the group or, if $0 is used, by the whole expression. See "More Examples" below for an example of using a backreference.
Tip: See the Java RegEx tutorial to learn about regular expressions.
Syntax
public String replaceAll(String regex, String replacement)
Parameter Values
Parameter | Description |
---|---|
regex | Required. A regular expression defining what substrings to search for. |
replacement | Required. The substring which will replace each match. |
Technical Details
Returns: | A copy of the string in which matches of the regular expression are replaced with new substrings. |
---|---|
Throws: | PatternSyntaxException - If the syntax of the regular expression is incorrect. |
Java version: | 1.4 |
More Examples
Example
Use a backreference to wrap numbers in parentheses:
String myStr = "Quest complete! Earned 30 gold and 500 experience.";
String regex = "[0-9]+";
System.out.println(myStr.replaceAll(regex, "($0)"));
❮ String Methods