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

正则表达式常规使用方式

时间:2015-07-27 22:40:55      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

正则表达式常规使用方式:
    Pattern:正则表达式的编译表示形式。   即每个Pattern对象代表一个规则!
 
   没有构造方法,使用以下方法返回Pettern对象
   public static Pattern compile(String regex) 将给定的正则表达式编译到模式中。通过给定的字符串形式正则创建对应的Pattern对象
   
   public Matcher matcher(CharSequence input) 使用Pattern对象匹配要被匹配的字符串,返回一个匹配器对象
 
     public boolean matches()  尝试将整个区域与模式匹配。
   public boolean find() 尝试查找与该模式匹配的输入序列的下一个子序列。  字符串中是否有符合匹配规则的内容
   public String group() 返回由以前匹配操作所匹配的输入子序列。  将字符串中符合匹配规则的内容返回
   public int end() 返回匹配到内容的尾部索引
   public int start() 返回匹配到内容的初始索引
 
  正则常规使用步骤:
  1:Pattern p = Pattern.compile("a*b");  使用规则生成Pattern对象
  2:Matcher m = p.matcher("aaaaab");  调用Pattern对象的matcher方法匹配要匹配的字符串返回匹配器对象(匹配引擎)
  3:boolean b = m.matches();  调用匹配器的方法,依据需求将内容与规则匹配。


例如:
  //指定字符串的正则规则
  String regex = "\\b[a-z]{3}\\b";
  //调用Pattern的方法,匹配一个规则,返回一个Pattern对象
  Pattern pattern = Pattern.compile(regex);
  //调用matcher方法,匹配某个字符串,返回匹配器对象
  //被匹配的字符串
  String str = "da jia zhu yi le, ming tian bu fang jia, xie xie!";
  Matcher matcher = pattern.matcher(str);
 
  //调用Matcher的方法,完成需求
  while(matcher.find()) {
   System.out.println(matcher.start()+"..."+matcher.end());
   System.out.println("sub:"+str.substring(matcher.start(),matcher.end()));

// System.out.println(matcher.group());

正则表达式常规使用方式

标签:

原文地址:http://www.cnblogs.com/javalei/p/4681215.html

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