Java正则表达式Pattern和Matcher原理详解

2020-02-25 14:00:43刘景俊

Mathcer.start()/ Matcher.end()/ Matcher.group()

当使用matches(),lookingAt(),find()执行匹配操作后,就可以利用以上三个方法得到更详细的信息.

start()返回匹配到的子字符串在字符串中的索引位置. end()返回匹配到的子字符串的最后一个字符在字符串中的索引位置. 即为最后位置加一 group()返回匹配到的子字符串

Java代码示例:

Pattern p=Pattern.compile("d+"); 
Matcher m=p.matcher("aaa2223bb"); 
m.find();//匹配2223 
m.start();//返回3 
m.end();//返回7,返回的是2223后的索引号 
m.group();//返回2223 

Mathcer m2=p.matcher("2223bb"); 
m2.lookingAt();  //匹配2223 
m2.start();  //返回0,由于lookingAt()只能匹配前面的字符串,所以当使用lookingAt()匹配时,start()方法总是返回0 
m2.end();  //返回4 
m2.group();  //返回2223 

Matcher m3=p.matcher("2223"); //如果Matcher m3=p.matcher("2223bb"); 那么下面的方法出错,因为不匹配返回false
m3.matches();  //匹配整个字符串 
m3.start();  //返回0
m3.end();  //返回3,原因相信大家也清楚了,因为matches()需要匹配所有字符串 
m3.group();  //返回2223

说了这么多,相信大家都明白了以上几个方法的使用,该说说正则表达式的分组在java中是怎么使用的.

start(),end(),group()均有一个重载方法它们是start(int i),end(int i),group(int i)专用于分组操作,Mathcer类还有一个groupCount()用于返回有多少组.

Java代码示例:

Pattern p=Pattern.compile("([a-z]+)(d+)"); 
Matcher m=p.matcher("aaa2223bb"); 
m.find();  //匹配aaa2223 
m.groupCount();  //返回2,因为有2组 
m.start(1);  //返回0 返回第一组匹配到的子字符串在字符串中的索引号 
m.start(2);  //返回3 
m.end(1);  //返回3 返回第一组匹配到的子字符串的最后一个字符在字符串中的索引位置. 
m.end(2);  //返回7 
m.group(1);  //返回aaa,返回第一组匹配到的子字符串 
m.group(2);  //返回2223,返回第二组匹配到的子字符串

验证手机号

// 验证手机号
    Pattern compile = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");
    Matcher matcher1 = compile.matcher("15071089603");
    while(matcher1.find()){
      System.out.println(matcher1.group());
    }

/**
   * 验证手机号码
   *
   * 移动号码段:139、138、137、136、135、134、150、151、152、157、158、159、182、183、187、188、147、182
   * 联通号码段:130、131、132、136、185、186、145
   * 电信号码段:133、153、180、189、177
   *
   */
 String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,1,2,5-9])|(177))d{8}$";

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。