Replacing parts of Strings

suggest change

Two ways to replace: by regex or by exact match.

Note: the original String object will be unchanged, the return value holds the changed String.

Exact match

Replace single character with another single character:

String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String s = "popcorn";
System.out.println(s.replace('p','W'));

Result:

WoWcorn

Replace sequence of characters with another sequence of characters:

String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
String s = "metal petal et al.";
System.out.println(s.replace("etal","etallica"));

Result:

metallica petallica et al.

Regex

Note: the grouping uses the $ character to reference the groups, like $1.

Replace all matches:

String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
String s = "spiral metal petal et al.";
System.out.println(s.replaceAll("(\\w*etal)","$1lica"));

Result:

spiral metallica petallica et al.

Replace first match only:

String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement
String s = "spiral metal petal et al.";
System.out.println(s.replaceAll("(\\w*etal)","$1lica"));

Result:

spiral metallica petal et al.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents