温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java正则怎么匹配手机号

发布时间:2026-07-24 05:59:06 来源:亿速云 阅读:152 作者:小樊 栏目:编程语言

在 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}$";

支持号段

  • 移动 / 联通 / 电信
  • 包含 13x、14x、15x、16x、17x、18x、19x

✅ 适合对手机号合法性要求较高的场景


✅ 三、宽松匹配(只要 11 位)

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 的手机号,我也可以帮你写对应正则。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI