Replace string using regex - Java Regular Expressions

Java examples for Regular Expressions:Replace

Description

Replace string using regex

Demo Code



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

public class Main {
  private static String REGEX = "dog";
  private static String INPUT = "The dog says meow. " + "All dogs say meow.";
  private static String REPLACE = "cat";

  public static void main(String[] args) {
    Pattern p = Pattern.compile(REGEX);

    // get a matcher object
    Matcher m = p.matcher(INPUT);
    INPUT = m.replaceAll(REPLACE);/*ww w.  j av a  2s . c om*/
    System.out.println(INPUT);
  }
}

Related Tutorials