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(Utils.join("", "Replace First 1: ", Pattern.compile("\\.\\.\\.").matcher(s).replaceFirst("!!!"))); System.out.println(Utils.join("", "Replace First 2: ", Pattern.compile("\\b...\\b").matcher(s).replaceFirst("???"))); System.out.println(Utils.join("", "Replace First 3: ", Pattern.compile("b.d").matcher(s).replaceFirst("???"))); System.out.println(Utils.join("", "Replace First 4: ", Pattern.compile("(\\w+) (\\w+)").matcher(s).replaceFirst("$2 $1"))); System.out.println(Utils.join("", "Replace All 1: ", Pattern.compile("\\b...\\b").matcher(s).replaceAll("???"))); System.out.println(Utils.join("", "Replace All 2: ", Pattern.compile("(\\w+) (\\w+)").matcher(s).replaceAll("$2 $1"))); } }