java中使用正則表達式:測試模式

import com.sun.org.apache.regexp.internal.RE;


public class regex {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
         String pattern="^Q[^u]\\d+\\.";
         String input="QA777. is the next flight,It is on time.";
         RE r=new RE(pattern);
         boolean found=r.match(input);
         System.out.println(pattern+(found ? "匹配" :"不匹配")+input);
         //以Q開頭並以.結尾,中間有多個字符
}


}

輸出結果:

^Q[^u]\d+\.匹配QA777. is the next flight,It is on time.


正則表達式公共API很大,它在程序中匹配的一般步驟是:

1.通過調用靜態方法Pattern.compile()創建一個模式;

2.爲每一個String調用pattern.matcher(CharSequence)以從模式中請求一個matcher;

3在結果中調用一次或多次finder方法;


例如:

Matcher m= Pattern.compile(patt).matcher(line);

if(m.find())

System.out.println(line+"matches"+patt);



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章