1.java中使用正則表達式進行檢驗字符串的格式
使用下面的代碼,如果需要校驗的字符串滿足正則表達式,返回true,否則返回false!
Pattern.compile(regularExpression).matcher(string).matches();
2.使用示例
1)手機號碼校驗:必須是以1開頭的11位純數字
public static boolean isMobile(String str) {
String regular = "^[1][\\d]{10}$";
return Pattern.compile(p).matcher(str).matches();
}
2)發票稅號校驗:必須是大寫字母和數字的組合,長度爲15,18或20位
public static boolean checkTaxNo(String taxpayerIdentity){
String regEx="^[A-Z0-9]{15}$|^[A-Z0-9]{18}$|^[A-Z0-9]{20}$";
return taxpayerIdentity.matches(regEx);
}
3)郵政編碼校驗:必須是6位數字的組合
public static boolean isZipNo(String zipString){
String str = "^[1-9][0-9]{5}$";
//String str = "^[//d]{6}$";
return Pattern.compile(str).matcher(zipString).matches();
}