Difference between String replace() and replaceAll()
What's the difference between java.lang.String 's replace()
and replaceAll()
methods,
other than later uses regex? For simple substitutions like, replace .
with /
,
is there any difference?
Solution 1:
In java.lang.String
, the replace
method either takes a pair of char's or a pair of CharSequence
's (of which String is a subclass, so it'll happily take a pair of String's). The replace
method will replace all occurrences of a char or CharSequence
. On the other hand, the first String
arguments of replaceFirst
and replaceAll
are regular expressions (regex). Using the wrong function can lead to subtle bugs.
Solution 2:
Q: What's the difference between the java.lang.String
methods replace()
and replaceAll()
, other than that the latter uses regex.
A: Just the regex. They both replace all :)
http://docs.oracle.com/javase/8/docs/api/java/lang/String.html
PS:
There's also a replaceFirst()
(which takes a regex)
Solution 3:
Both replace()
and replaceAll()
replace all occurrences in the String.
Examples
I always find examples helpful to understand the differences.
replace()
Use replace()
if you just want to replace some char
with another char
or some String
with another String
(actually CharSequence
).
Example 1
Replace all occurrences of the character x
with o
.
String myString = "__x___x___x_x____xx_";
char oldChar = 'x';
char newChar = 'o';
String newString = myString.replace(oldChar, newChar);
// __o___o___o_o____oo_
Example 2
Replace all occurrences of the string fish
with sheep
.
String myString = "one fish, two fish, three fish";
String target = "fish";
String replacement = "sheep";
String newString = myString.replace(target, replacement);
// one sheep, two sheep, three sheep
replaceAll()
Use replaceAll()
if you want to use a regular expression pattern.
Example 3
Replace any number with an x
.
String myString = "__1_6____3__6_345____0";
String regex = "\\d";
String replacement = "x";
String newString = myString.replaceAll(regex, replacement);
// __x_x____x__x_xxx____x
Example 4
Remove all whitespace.
String myString = " Horse Cow\n\n \r Camel \t\t Sheep \n Goat ";
String regex = "\\s";
String replacement = "";
String newString = myString.replaceAll(regex, replacement);
// HorseCowCamelSheepGoat
See also
Documentation
replace(char oldChar, char newChar)
replace(CharSequence target, CharSequence replacement)
replaceAll(String regex, String replacement)
replaceFirst(String regex, String replacement)
Regular Expressions
- Tutorial
- List of patterns