Share this page 

Replace every occurences of a string within a stringTag(s): String/Number


String.replaceAll() replaces each substring of this String that matches the given regular expression with the given replacement. Remember that StringreplaceAll() returns a new String so keep the result!

[JDK1.4]

public class Test{
  public static void main(String[] args){
    String text = "hello world from www.rgagnon.com : hello world";

    // replace all
    String result = text.replaceAll("(?:hello world)", "bonjour le monde");
    System.out.println(result);

    // replace only the first match
    result = text.replaceFirst("(?:hello world)", "bonjour le monde");
    System.out.println(result);
      
    /*
      
      output :
      bonjour le monde from www.rgagnon.com : bonjour le monde
      bonjour le monde from www.rgagnon.com : hello world
      
    */  
  }
}
Keep in mind, that you need to escape characters like $ or | since they have special meaning when used in a regular expression. It can be quite an adventure to deal with the "\" since it is considered as an escape character in Java. You always need to "\\" a "\" in a String. But the fun begins when you want to use a "\" in regex expression, because the "\" is an escape character in regex too. So for a single "\" you need to use "\\\\" in a regex expression.
public class Test {
  public static void main(String[] args){
    String text = "\\\\server\\apps\\file.txt";
    System.out.println("original : " + text);
    System.out.println("converted : " + text.replaceAll("\\\\","\\\\\\\\"));
    /*
     output :
         original : \\server\apps\file.txt
         converted : \\\\server\\apps\\file.txt
     */
  }
}

Since replaceAll() is based on a regex expression, it is very easy to make the substituion case insensitive.

public class Test {
  public static void main(String[] args) {
    String test = "Real's hoWTo"; 
    System.out.println("original : " + test);
    test= test.replaceAll("(?i)howto", "HowTo");
    System.out.println("converted : " + test);  // output : Real's HowTo
  }
}

[ < JDK1.4]
String,replaceAll() is not available with Java version older than 1.4, you need to code the substitution. This snippet provides a simple replacesAll() equivalent.

public static String replaceAll(String target, String from, String to) {   
  //   target is the original string
  //   from   is the string to be replaced
  //   to     is the string which will used to replace
  //  returns a new String!
  int start = target.indexOf(from);
  if (start == -1) return target;
  int lf = from.length();
  char [] targetChars = target.toCharArray();
  StringBuffer buffer = new StringBuffer();
  int copyFrom = 0;
  while (start != -1) {
    buffer.append (targetChars, copyFrom, start - copyFrom);
    buffer.append (to);
    copyFrom = start + lf;
    start = target.indexOf (from, copyFrom);
    }
  buffer.append (targetChars, copyFrom, targetChars.length - copyFrom);
  return buffer.toString();
}