业余草 Java正则表达式,验证手机号和电话号码

Java 正则表达式

正则表达式定义了字符串的模式。

正则表达式可以用来搜索、编辑或处理文本。

正则表达式并不仅限于某一种语言,但是在每种语言中有细微的差别。

正则表达式实例

一个字符串其实就是一个简单的正则表达式,例如 Hello World 正则表达式匹配 "Hello World" 字符串。

.(点号)也是一个正则表达式,它匹配任何一个字符如:"a" 或 "1"。

下表列出了一些正则表达式的实例及描述:

正则表达式 描述

this is text

匹配字符串 "this is text"

this\s+is\s+text

注意字符串中的 \s+

匹配单词 "this" 后面的 \s+ 可以匹配多个空格,之后匹配 is 字符串,再之后 \s+ 匹配多个空格然后再跟上 text 字符串。

可以匹配这个实例:this is text

^\d+(\.\d+)?

^ 定义了以什么开始

\d+ 匹配一个或多个数字

? 设置括号内的选项是可选的

\. 匹配 "."

可以匹配的实例:"5", "1.5" 和 "2.21"。

Java 正则表达式和 Perl 的是最为相似的。

java.util.regex 包主要包括以下三个类:

  • Pattern 类:

    pattern 对象是一个正则表达式的编译表示。Pattern 类没有公共构造方法。要创建一个 Pattern 对象,你必须首先调用其公共静态编译方法,它返回一个 Pattern 对象。该方法接受一个正则表达式作为它的第一个参数。

  • Matcher 类:

    Matcher 对象是对输入字符串进行解释和匹配操作的引擎。与Pattern 类一样,Matcher 也没有公共构造方法。你需要调用 Pattern 对象的 matcher 方法来获得一个 Matcher 对象。

  • PatternSyntaxException:

    PatternSyntaxException 是一个非强制异常类,它表示一个正则表达式模式中的语法错误。

 /**
   * 获取当前的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("不符合");
    }
  }

  

如有疑问,欢迎关注微信公众号“业余草”!

猜你喜欢

转载自www.cnblogs.com/panda2/p/9246553.html