Welcome to my blog, hope you enjoy reading
RSS

Tuesday 20 May 2014

replace() vs replaceAll()

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.

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.



package com.javanotes2all.java.string;

public class ReplacevsReplaceAll {
 public static void main(String[] args) {
  
  /*
   * Example1- For normal string both are same
   */
  String s="javanotes2all";
  
  System.out.println("For one character replace");
  System.out.println("replace():   "+s.replace("a", "-"));
  System.out.println("replaceAll():   "+s.replaceAll("a", "-"));
  
  System.out.println("\nFor more characters replace");
  System.out.println("replace():   "+s.replace("av", "-"));
  System.out.println("replaceAll():   "+s.replaceAll("av", "-"));
  
  /*
   * Example2- For Regular expressions both are different
   */
  s="javanotes2all_$_prabhu _java $ notes";
  
  System.out.println("\nFor Regular expressions");
  /*
   * replace method replaces all characters match
   */
  System.out.println("replace():   "+s.replace("_$_", "-"));
  /*
   * This is not replacing 
   */
  System.out.println("replaceAll():   "+s.replaceAll("_$_", "-"));
  
  /*
   * This is replacing characters 
   */
  System.out.println("replaceAll():   "+s.replaceAll("\\_\\$\\_", "-"));
  
 }
}

0 comments: