Monday, August 12, 2013

replace vs replaceAll in Java (Difference between replace and replace All)



Sometimes we do some silly mistake unintentionally.

Assuming replace() will replace first instance of String found in the entire String, and replaceAll() will replace all the instances of the Strings, is one of them.

When I realized this mistake of mine few years back, I curiously wanted to know what my fellow developers think about it.Interestingly, most of them were living with the same misconception.In fact they are really good Java programmers.
 
Hence, don't go by the name, Java has some other meaning tagged to it.

Both replace() and replaceAll() replaces all the occurrence found. However, there is difference in the type of arguments they accept.

replace() works on CharSequence, where as replaceAll(), accepts regex, so you can do a regular expression based pattern matching. The later is more flexible, but might result in a bit of performance overhead of compiling the regex and then do a matching. For smaller String replacements, you might not need to think much.  


 Quoting Java Doc:


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.
          



PS: CharSequence is one of the interface implemented by String class.

If you see the Java Doc for String class, String implements Serializable, CharSequence and Comparable<String>.
So, dont get confused by CharSequence, normally you can pass String as input to replace() function because of above reason.

And yes, for repacling only the first occurance of a char sequence, you can use replaceFirst(String regex, String replacement) method of String class.
           

2 comments:

Prototype

Prototype is another creation pattern. Intent:  - Intent is to create objects by cloning existing instance  - Specify the kinds of obj...