表單驗證、註冊流程、短信發送前檢核等場景,皆需確認使用者輸入的手機號碼格式正確。中國大陸手機號碼為 11 位數字,開頭號段隨運營商政策持續擴展。
^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$
^ $:全字串比對13[0-9]:130-139 全段15[^4,\\D]:150-159 排除 154 及非數字(舊寫法,現 154 已開放)18[0,5-9]:180、185-189\\d{8}:後續 8 位任意數字import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class MobileValidator {
// 建議定期更新號段
private static final Pattern MOBILE_PATTERN = Pattern.compile(
"^(13\\d|14[0-9]|15\\d|16\\d|17\\d|18\\d|19\\d)\\d{8}$"
);
public static boolean isMobileNO(String mobile) {
if (mobile == null || mobile.length() != 11) return false;
Matcher m = MOBILE_PATTERN.matcher(mobile);
return m.matches();
}
public static void main(String[] args) {
String[] tests = {"13800138000", "15412345678", "19988889999", "12345678901", "1380013800"};
for (String s : tests) {
System.out.printf("%s -> %b%n", s, isMobileNO(s));
}
}
}
13800138000 -> true
15412345678 -> true
19988889999 -> true
12345678901 -> false
1380013800 -> false