Java Regular Expression String replace all

Introduction

Java String replaceAll() method can accept Matcher and perform search and replace operations.

For example, the following program replaces all occurrences of sequences that begin with "CSS" with "HTML":

// Use replaceAll(). 
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String args[]) {
    String str = "CSS CSSTutorial HTML5";

    Pattern pat = Pattern.compile("CSS.*? ");
    Matcher mat = pat.matcher(str);

    System.out.println("Original sequence: " + str);

    str = mat.replaceAll("HTML ");

    System.out.println("Modified sequence: " + str);

  }//from   ww  w.  j av  a  2 s.c o  m
}



PreviousNext

Related