正则2 -- pattern和Matcher

Pattern

  正则表达式的编译表示形式。

  典型的调用顺序  

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class demon8_patternAndMatcher {
    /*
     * 典型的调用顺序是 
     Pattern p = Pattern.compile("a*b");
     Matcher m = p.matcher("aaaaab");
     boolean b = m.matches();   
     */
    public static void main(String[] args) {
        //  获取手机号
        String s1 = "我的手机号码是18988888888,曾经用过13312345678,还用过15386754321";
        String regex = "1[3578]\\d{9}";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(s1);
        while (m.find()) {    //find()  重置此匹配器,然后尝试查找匹配该模式、从指定索引开始的输入序列的下一个子序列。
            System.out.println(m.group());   // group()  返回由以前匹配操作所匹配的输入子序列。
            
        }
        // 一定要先find()  ,再group() 获取  
    }

}

猜你喜欢

转载自www.cnblogs.com/yaobiluo/p/11302109.html
今日推荐