本文章转自: http://blog.csdn.net/cclovett/article/details/12448843
结论:Pattern与Matcher一起合作.Matcher类提供了对正则表达式的分组支持,以及对正则表达式的多次匹配支持. 单独用Pattern只能使用Pattern.matcher(String regex,CharSequence input)一种最基础最简单的匹配。
Pattern p=Pattern.compile('\\d+'); String[] str=p.split('我的QQ是:456456我的电话是:0532214我的邮箱是:aaa@aaa.com');
Pattern.matches('\\d+','2223');//返回truePattern.matches('\\d+','2223aa');//返回false,需要匹配到所有字符串才能返回true,这里aa不能匹配到Pattern.matches('\\d+','22bb23');//返回false,需要匹配到所有字符串才能返回true,这里bb不能匹配到
Pattern p=Pattern.compile('\\d+');Matcher m=p.matcher('22bb23'); m.pattern();//返回p 也就是返回该Matcher对象是由哪个Pattern对象的创建的
1 Pattern p=Pattern.compile('\\d+');2 Matcher m=p.matcher('22bb23');3 m.matches();//返回false,因为bb不能被\d+匹配,导致整个字符串匹配未成功.4 Matcher m2=p.matcher('2223');5 m2.matches();//返回true,因为\d+匹配到了整个字符串
Pattern p=Pattern.compile('\\d+');Matcher m=p.matcher('22bb23');m.lookingAt();//返回true,因为\d+匹配到了前面的22Matcher m2=p.matcher('aa2223');m2.lookingAt();//返回false,因为\d+不能匹配前面的aa find()对字符串进行匹配,匹配到的字符串可以在任何位置. Pattern p=Pattern.compile('\\d+');Matcher m=p.matcher('22bb23');m.find();//返回trueMatcher m2=p.matcher('aa2223');m2.find();//返回trueMatcher m3=p.matcher('aa2223bb');m3.find();//返回trueMatcher m4=p.matcher('aabb');m4.find();//返回false
1 Pattern p=Pattern.compile('\\d+'); 2 Matcher m=p.matcher('aaa2223bb'); 3 m.find();//匹配2223 4 m.start();//返回3 5 m.end();//返回7,返回的是2223后的索引号 6 m.group();//返回2223 7 8 Mathcer m2=p.matcher('2223bb'); 9 m2.lookingAt(); //匹配222310 m2.start(); //返回0,由于lookingAt()只能匹配前面的字符串,所以当使用lookingAt()匹配时,start()方法总是返回011 m2.end(); //返回412 m2.group(); //返回222313 14 Matcher m3=p.matcher('2223'); //如果Matcher m3=p.matcher('2223bb'); 那么下面的方法出错,因为不匹配返回false15 m3.matches(); //匹配整个字符串16 m3.start(); //返回017 m3.end(); //返回3,原因相信大家也清楚了,因为matches()需要匹配所有字符串18 m3.group(); //返回2223
1 Pattern p=Pattern.compile('([a-z]+)(\\d+)'); 2 Matcher m=p.matcher('aaa2223bb'); 3 m.find(); //匹配aaa2223 4 m.groupCount(); //返回2,因为有2组 5 m.start(1); //返回0 返回第一组匹配到的子字符串在字符串中的索引号 6 m.start(2); //返回3 7 m.end(1); //返回3 返回第一组匹配到的子字符串的最后一个字符在字符串中的索引位置. 8 m.end(2); //返回7 9 m.group(1); //返回aaa,返回第一组匹配到的子字符串10 m.group(2); //返回2223,返回第二组匹配到的子字符串
1 Pattern p=Pattern.compile('\\d+');2 Matcher m=p.matcher('我的QQ是:456456 我的电话是:0532214 我的邮箱是:aaa123@aaa.com');3 while(m.find()) {4 System.out.println(m.group());5 } 输出: 1 while(m.find()) {2 System.out.println(m.group());3 System.out.print('start:'+m.start());4 System.out.println(' end:'+m.end());5 } 则输出:
|
|