码迷,mamicode.com
首页 > 其他好文 > 详细

Pattern 和 Matcher

时间:2017-02-16 23:22:48      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:匹配   public   lock   正则表达式   highlight   .com   案例   手机   pat   

作用:应用这个 Pattern 和 Matcher 可以完成字符串获取功能

 


使用:

// 获取模式器对象

Pattern p = Pattern.compile("a*b") ;

// 获取匹配器对象

Mather m = p.matcher("aaaaab") ;

// 调用方法

public boolean matches(): 校验

public boolean find(): 查找

public String group(): 获取

 


public class Demo8_Pattern {
   /**

    * Pattern p = Pattern.compile("a*b");

       Matcher m = p.matcher("aaaaab");

       boolean b = m.matches();      

      * A:正则表达式的获取功能

         * Pattern和Matcher的结合使用

      * B:案例演示

         * 需求:把一个字符串中的手机号码获取出来

    */

   public static void main(String[] args) {
      //demo1();
      String s = "我的手机是18988888888,我曾用过18987654321,还用过18812345678";
      String regex = "1[3578]\\d{9}";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(s);
      /*boolean b1 = m.find();
      System.out.println(b1);
      System.out.println(m.group());    
      boolean b2 = m.find();
      System.out.println(b2);
      System.out.println(m.group());*/
      while(m.find())
         System.out.println(m.group());
   }
   public static void demo1() {
      Pattern p = Pattern.compile("a*b");               //获取到正则表达式
      Matcher m = p.matcher("aaaaab");               //获取匹配器
      boolean b = m.matches();                    //看是否能匹配,匹配就返回true
      System.out.println(b);
      System.out.println("aaaaab".matches("a*b"));      //与上面的结果一样
   }
}

 

 

 

Pattern 和 Matcher

标签:匹配   public   lock   正则表达式   highlight   .com   案例   手机   pat   

原文地址:http://www.cnblogs.com/loaderman/p/6407308.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!