在 Java 中,匹配中国大陆手机号一般使用正则表达式。下面给你几种常见、实用的写法,从简单到较严谨。
匹配 13/14/15/16/17/18/19 开头的 11 位手机号
String regex = "^1[3-9]\\d{9}$";
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String phone = "13812345678";
String regex = "^1[3-9]\\d{9}$";
boolean match = Pattern.matches(regex, phone);
System.out.println(match); // true
}
}
✅ 说明
1:手机号必须以 1 开头[3-9]:第二位不能是 0/1/2\d{9}:后面 9 位数字^ 和 $:严格匹配整个字符串如果你希望精确匹配真实号段:
String regex = "^1(3\\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\\d|9[0-35-9])\\d{8}$";
✅ 适合对手机号合法性要求较高的场景
String regex = "^\\d{11}$";
⚠️ 不推荐用于正式校验,但适合简单场景
如果你要从一段文字中提取手机号:
import java.util.regex.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
String text = "我的手机号是13812345678,另一个是15900001111";
String regex = "1[3-9]\\d{9}";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println(m.group());
}
}
}
❌ 忘记转义 \d
"1[3-9]\d{9}" // 错误
"1[3-9]\\d{9}" // 正确
❌ 误用 String.matches() 时忘记 ^ $
phone.matches("1[3-9]\\d{9}"); // 实际等价于 ^...$
| 场景 | 正则 |
|---|---|
| 一般校验 | ^1[3-9]\\d{9}$ ✅ |
| 精确号段 | `^1(3\d |
| 文本提取 | 1[3-9]\\d{9} |
如果你需要 校验国际手机号 或 带 +86 的手机号,我也可以帮你写对应正则。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。