Java Reference ยท java.lang
Java String.replace() method
Reference for Java String.replace(), replaceAll() and replaceFirst(): literal vs regex replacement, group references, immutability and common mistakes.
Java has three replacement methods on String. replace() swaps every occurrence of a literal character or text. replaceAll() and replaceFirst() treat the first argument as a regular expression and allow group references such as $1 in the replacement.
All three return a new string. Strings are immutable, so calling s.replace("a", "b") without using the result does nothing.
"banana".replace("a", "o"); // "bonono" "a1b22".replaceAll("\\d+", "#"); // "a#b#" "a1b22".replaceFirst("\\d+", "#"); // "a#b22"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) public String replaceAll(String regex, String replacement) public String replaceFirst(String regex, String replacement)
| Name | Description |
|---|---|
oldChar, target |
The literal character or text to find. |
newChar, replacement |
What to put in its place (for replace, taken literally). |
regex |
A regular expression (for replaceAll and replaceFirst). |
Returns: a new string; the same object if nothing matched (for the char form).
Throws: PatternSyntaxException for a bad regex; IllegalArgumentException or IndexOutOfBoundsException for a malformed $ group reference in the replacement; NullPointerException for null arguments.
Usage notes
- Prefer
replace()for plain text. It is literal, faster and has no escaping traps. Despite its name it replaces all occurrences. replaceAll()uses a regex..,*,|,(,[and\have special meaning in the first argument.- The replacement string is special too in
replaceAllandreplaceFirst:$1inserts a group and\escapes. UseMatcher.quoteReplacement()for arbitrary text. - Immutable. Always assign the result:
s = s.replace(...). - Empty target.
"x".replace("", "-")inserts the replacement between every character and at both ends. - Replacements are not recursive. Replaced text is not searched again, so
"aaa".replace("aa", "a")gives"aa". - Many replacements in a loop create many intermediate strings; for heavy work use
Matcher.replaceAll(Function)(Java 9) or aStringBuilder. - Case-insensitive:
replaceAll("(?i)hello", "hi"). - Computed replacement:
Pattern.compile(...).matcher(s).replaceAll(m -> m.group().toUpperCase()).