package TestRegex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test01 {
/**
* 郵政編碼正則:"^[1-9]\\d{5}$"
* ^:正則開始符
* $:正則結束符
* [1-9]:范圍為1-9
* \:轉移字符
* \d:數字【0-9】
* X{n}:恰好n次:注意從0開始
*/
public static void main(String[] args) {
//定義正則
String str= "^[1-9]\\d{5}$";
//正確的郵件編碼
String s = "471400";
//錯誤郵政編碼
String s2 ="4560200";
/**
* Pattern為模式類型,
* compile(正則)方法預編譯正則,
* 得到一個Matcher對象
*/
Pattern p =Pattern.compile(str);
//Pattern中的matcher()方法傳入要匹配的字符串與正則進行匹配i
Matcher m=p.matcher(s);
Matcher m2=p.matcher(s2);
//Matcher類中的matches()方法判斷是否匹配成功
boolean bo= m.matches();
boolean bo2= m2.matches();
//輸出匹配結果:true為成功,false為失敗
System.out.println(bo);
System.out.println(bo2);
}
}
運行結果:


