Java正則表示式——驗證手機號和電話號碼
阿新 • • 發佈:2019-01-31
一個朋友需要,所以寫了這兩個,話不都說,看程式碼
/** * 獲取當前的httpSession * @author :shijing * 2016年12月5日下午3:46:02 * @return */ public static HttpSession getSession() { return getRequest().getSession(); } /** * 手機號驗證 * @author :shijing * 2016年12月5日下午4:34:46 * @param str * @return 驗證通過返回true */ public static boolean isMobile(final String str) { Pattern p = null; Matcher m = null; boolean b = false; p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 驗證手機號 m = p.matcher(str); b = m.matches(); return b; } /** * 電話號碼驗證 * @author :shijing * 2016年12月5日下午4:34:21 * @param str * @return 驗證通過返回true */ public static boolean isPhone(final String str) { Pattern p1 = null, p2 = null; Matcher m = null; boolean b = false; p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$"); // 驗證帶區號的 p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$"); // 驗證沒有區號的 if (str.length() > 9) { m = p1.matcher(str); b = m.matches(); } else { m = p2.matcher(str); b = m.matches(); } return b; } public static void main(String[] args) { String phone = "13900442200"; String phone2 = "021-88889999"; String phone3 = "88889999"; String phone4 = "1111111111"; //測試1 if(isPhone(phone) || isMobile(phone)){ System.out.println("1這是符合的"); } //測試2 if(isPhone(phone2) || isMobile(phone2)){ System.out.println("2這是符合的"); } //測試3 if(isPhone(phone3) || isMobile(phone3)){ System.out.println("3這是符合的"); } //測試4 if(isPhone(phone4) || isMobile(phone4)){ System.out.println("4這是符合的"); }else{ System.out.println("不符合"); } }