zhengze 四 buhuo 与 not bu huo

来源:互联网 发布:淘宝手机我的店铺 编辑:程序博客网 时间:2024/06/03 20:43
定义:要对多个字符进行重复,用小括号(),来指定要重复的自表达式,然后对这个表达式进行重复。如:(abc)?表示0个或1个abc
1.捕获组:正则表达式中每个“()”内的部分算作一个捕获组,每个捕获组都有一个编号,从1,2,3.....编号0代表整个匹配到的内容。


String content="<title weight='120px'>nihao</title>";
Pattern p=Pattern.compile("(<title .*?>)(.*)(</title>)");
Matcher m=p.matcher(content);
 if(m.find()){
   System.out.println(m.group(0)+"=="+m.start());
   System.out.println(m.group(1)+"=="+m.start());
   System.out.println(m.group(2)+"=="+m.start());
   System.out.println(m.group(3)+"=="+m.start());
  }
 else{
 System.out.println("没有匹配到!!!");
 }
//结果为:<title weight='120px'>nihao</title>==0
<title weight='120px'>==0
nihao==0
</title>==0




2.非捕获组:如果小括号中以?开头,那么这个分组就不会捕获文本,也不会有组编号,因此也不存在回溯引用。


(?:x) 匹配x,但不捕获匹配结果。
(?=x) 零宽度正预测先行断言,但不捕获匹配结果。
(?!x)    零宽度负预测先行断言,但不捕获匹配结果。
(?<=x) 零宽度正预测后发断言,但不捕获匹配结果。
(?<!x)零宽度负预测后发断言,但不捕获匹配结果。
(?:x)与后面4个非捕获组的区别在:
(?:x) :匹配x,group(0)匹配结果包括x
后面4个:匹配x(或不匹配x)位置之前(或之后)的内容,group(0)时匹配的不包括x;
(?:x)与(x)在于只匹配,不捕获结果。

String content="<title weight='120px'>nihao</title>";
Pattern p=Pattern.compile("(?:<title .*?>)(.*)(?:</title>)");
Matcher m=p.matcher(content);
 if(m.find()){
   System.out.println(m.group(0)+"=="+m.start());
   System.out.println(m.group(1)+"=="+m.start());
   System.out.println(m.group(2)+"=="+m.start());
   System.out.println(m.group(3)+"=="+m.start());
  }
 else{
 System.out.println("没有匹配到!!!");
 }
结果:
<title weight='120px'>nihao</title>==0
nihao==0
Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 2
因为不存在编号为2的捕获组


String content="<title weight='120px'>nihao</title>";
Pattern p=Pattern.compile("(?:<title .*?>)(.*)(?:</title>)");
Matcher m=p.matcher(content);
 if(m.find()){
   System.out.println(m.group(0)+"=="+m.start());
   System.out.println(m.group(1)+"=="+m.start());
  // System.out.println(m.group(2)+"=="+m.start());
   //System.out.println(m.group(3)+"=="+m.start());
  }
 else{
 System.out.println("没有匹配到!!!");
 }
结果:
<title weight='120px'>nihao</title>==0
nihao==0
例子:
1、测试匹配性  (?<!4)56(?=9)这里的含义就是匹配后面的文本56前面不能是4,后面必须是9组成。因此,可以匹配如下文本 5569 ,与4569不匹配。
 2 、提取字符串  提取 da12bka3434bdca4343bdca234bm   提取包含在字符a和b之间的数字,但是这个a之前的字符不能是c,b后面的字符必须是d才能提取。
  String content="da12bka3434bdca4343bdca234bm";
Pattern p=Pattern.compile("(?<!c)a(\\d+)b(?=d)");
Matcher m=p.matcher(content);
 if(m.find()){
   System.out.println(m.group(0)+"=="+m.start());//a3434b,看到非捕获组均为显示结果(?<!c),(?=d)
   System.out.println(m.group(1)+"=="+m.start());//3434,0组是整个表达式,捕获组显示的结果:
   //System.out.println(m.group(2)+"=="+m.start());

   //System.out.println(m.group(3)+"=="+m.start());
  }
 else{
 System.out.println("没有匹配到!!!");
 }
http://www.jb51.net/article/28035.htm
http://blog.csdn.net/luojinbai/article/details/50082635
原创粉丝点击