What’s the difference between java.lang.String ‘s replace() and replaceAll() methods,
other than the latter uses regex? For simple substitutions like, replace . with /, is there any difference?
What’s the difference between java.lang.String ‘s replace() and replaceAll() methods, other than the latter
Share
java.lang.String, thereplacemethod either takes a pair of char’s or a pair ofCharSequence‘s (which String is implementing, so it’ll happily take a pair of String’s). Thereplacemethod will replace all occurrences of a char orCharSequence.Stringarguments ofreplaceFirstandreplaceAllare regular expressions (regex).Using the wrong function can lead to subtle bugs.
Relevant sections from
java.lang.String:String replace(char oldChar, char newChar)Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
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 replaceAll(String regex, String replacement)Replaces each substring of this string that matches the given regular expression with the given replacement.
String replaceFirst(String regex, String replacement)Replaces the first substring of this string that matches the given regular expression with the given replacement.