import java.util.regex.Pattern; import org.pureprogrammer.Utils; public class RegEx2 { public static void main(String[] args) { final String s = "Four score and seven years ago..."; System.out.println("Replace First 1: " + Pattern.compile("\\.\\.\\.").matcher(s).replaceFirst("!!!")); System.out.println("Replace First 2: " + Pattern.compile("\\b...\\b").matcher(s).replaceFirst("???")); System.out.println("Replace First 3: " + Pattern.compile("b.d").matcher(s).replaceFirst("???")); System.out.println("Replace First 4: " + Pattern.compile("(\\w+) (\\w+)").matcher(s).replaceFirst("$2 $1")); System.out.println("Replace All 1: " + Pattern.compile("\\b...\\b").matcher(s).replaceAll("???")); System.out.println("Replace All 2: " + Pattern.compile("(\\w+) (\\w+)").matcher(s).replaceAll("$2 $1")); } }