前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >Java正则表达式——验证手机号和电话号码

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

作者头像
执笔记忆的空白
发布2020-12-25 14:41:04
发布2020-12-25 14:41:04
7.1K00
代码可运行
举报
文章被收录于专栏:Java日常Java日常
运行总次数:0
代码可运行

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

代码语言:javascript
代码运行次数:0
复制
 /**
   * 获取当前的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("不符合");
    }
  }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016/12/05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档