Java Examples - Replace all occourances of a string


Problem Description:

How to replace all occurings of a string?


Following example demonstrates how to replace all occouranc of a String in a String using replaceAll() method of Matcher class.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("hello");
      String instring = "hello hello hello.";
      System.out.println("initial String: "+ instring);
      Matcher m = p.matcher(instring);
      String tmp = m.replaceAll("Java");
      System.out.println("String after replacing 1st Match: "


The above code sample will produce the following result.

initial String: hello hello hello.
String after replacing 1st Match: Java Java Java.