Java正则表达式——验证手机号和电话号码

本文提供了两种实用的方法来验证手机号及电话号码的有效性。通过正则表达式匹配,确保输入的手机号码符合中国常见的格式规范,并能区分带有区号的固定电话号码。

一个朋友需要,所以写了这两个,话不都说,看代码

/**

  • 获取当前的httpSession
  • @author :shijing
  • 2016年12月5日下午3:46:02
  • @return
    */
    public static HttpSession getSession() {
    return getRequest().getSession();
    }

    /**

  • 手机号验证
  • @author :shijing
  • 2016年12月5日下午4:34:46
  • @param str
  • @return 验证通过返回true
    */
    public static boolean isMobile(final String str) {
    Pattern p = null;
    Matcher m = null;
    boolean b = false;
    p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
    m = p.matcher(str);
    b = m.matches();
    return b;
    }
    /**
  • 电话号码验证
  • @author :shijing
  • 2016年12月5日下午4:34:21
  • @param str
  • @return 验证通过返回true
    */
    public static boolean isPhone(final String str) {
    Pattern p1 = null, p2 = null;
    Matcher m = null;
    boolean b = false;
    p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$"); // 验证带区号的
    p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$"); // 验证没有区号的
    if (str.length() > 9) {
    m = p1.matcher(str);
    b = m.matches();
    } else {
    m = p2.matcher(str);
    b = m.matches();
    }
    return b;
    }

    public static void main(String[] args) {
    String phone = "13900442200";
    String phone2 = "021-88889999";
    String phone3 = "88889999";
    String phone4 = "1111111111";
    //测试1
    if(isPhone(phone) || isMobile(phone)){
    System.out.println("1这是符合的");
    }
    //测试2
    if(isPhone(phone2) || isMobile(phone2)){
    System.out.println("2这是符合的");
    }
    //测试3
    if(isPhone(phone3) || isMobile(phone3)){
    System.out.println("3这是符合的");
    }
    //测试4
    if(isPhone(phone4) || isMobile(phone4)){
    System.out.println("4这是符合的");
    }else{
    System.out.println("不符合");
    }
    }

转载于:https://blog.51cto.com/13545923/2053326

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值