PhoneUtils.java
package com.common.util; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class PhoneUtils { /** * 大陸號碼或香港號碼都可以 * @param str * @return 符合規則返回true * @throws PatternSyntaxException */ public static boolean isPhoneLegal(String str) throws PatternSyntaxException { return isChinaPhoneLegal(str) || isHKPhoneLegal(str); } /** * * 大陸手機號碼11位數,匹配格式:前三位固定格式+后8位任意數 * 此方法中前三位格式有: * 13+任意數 * 145,147,149 * 15+除4的任意數(不要寫^4,這樣的話字母也會被認為是正確的) * 166 * 17+3,5,6,7,8 * 18+任意數 * 198,199 * @param str * @return 正確返回true * @throws PatternSyntaxException */ public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException { // ^ 匹配輸入字符串開始的位置 // \d 匹配一個或多個數字,其中 \ 要轉義,所以是 \\d // $ 匹配輸入字符串結尾的位置 String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" + "|(18[0-9])|(19[8,9]))\\d{8}$"; Pattern p = Pattern.compile(regExp); Matcher m = p.matcher(str); return m.matches(); } /** * 香港手機號碼8位數,5|6|8|9開頭+7位任意數 * @param str * @return 正確返回true * @throws PatternSyntaxException */ public static boolean isHKPhoneLegal(String str) throws PatternSyntaxException { // ^ 匹配輸入字符串開始的位置 // \d 匹配一個或多個數字,其中 \ 要轉義,所以是 \\d // $ 匹配輸入字符串結尾的位置 String regExp = "^(5|6|8|9)\\d{7}$"; Pattern p = Pattern.compile(regExp); Matcher m = p.matcher(str); return m.matches(); } }