2015年10月2日 星期五

正規化表示式

Pattern & Matcher 的應用:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegxDemo {
    public static void main(String[] args){
    
        String test = "He was a teacher";
        
        Pattern p1 = Pattern.compile("w.s");
        Matcher m1 = p1.matcher(test);
        if (m1.find()){
            System.out.println("Found: " + m1.group());
        }
        
        Pattern p2 = Pattern.compile("w[abc]s");
        Matcher m2 = p2.matcher(test);
        if (m2.find()){
            System.out.println("Found: " + m2.group());
        }
        
        Pattern p3 = Pattern.compile("t[^xyz]acher");
        Matcher m3 = p3.matcher(test);
        if (m3.find()){
            System.out.println("Found: " + m3.group());
        }

        String header = "<h1>Hello World<h1>";
        Pattern p4 = Pattern.compile("h1");
        Matcher m4 = p4.matcher(header);
        if (m4.find()){
            System.out.println("Found: " + m4.group());
            header = m4.replaceAll("p");
            System.out.println(header);
        }  

    }
}