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.
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
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.
Note: the grouping uses the $
character to reference the groups, like $1
.
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.
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.