手機號碼驗證是表單檢核常見需求。本文提供一個簡潔的靜態方法,使用正則表達式快速判斷字串是否符合中國大陸手機號碼格式(11 位數字,特定前綴)。
import java.util.regex.Pattern;
public class MobileValidator {
/**
* 驗證手機號碼格式
* @param mobiles 待驗證字串
* @return true 符合格式,false 否則
*/
public static boolean isMobileNumber(String mobiles) {
// 支援 13x、15x(除154)、18x(除181、184) 開頭的 11 位數字
return Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[^1^4,\\D]))\\d{8}$")
.matcher(mobiles)
.matches();
}
}
13[0-9]:130-13915[^4,\\D]:150-159 但排除 154 及非數字18[^1^4,\\D]:180-189 但排除 181、184 及非數字\\d{8}:後續 8 位數字System.out.println(MobileValidator.isMobileNumber("13812345678")); // true
System.out.println(MobileValidator.isMobileNumber("15412345678")); // false
System.out.println(MobileValidator.isMobileNumber("18912345678")); // true
號段隨時間增加,實際專案建議定期更新正則或使用專門的驗證庫(如 Google libphonenumber)。