强调在正则中只要单纯用了括号就会有捕获分组保存

来源:互联网 发布:python 运维框架 编辑:程序博客网 时间:2024/05/23 11:40

转载于:http://blog.csdn.net/marvel__dead/article/details/53365316

前言:

本篇文章主要为了强调正则中\1的引用,1为括号的编号。和不加不必要的括号,以防影响效率。

import java.util.regex.Matcher;import java.util.regex.Pattern;public class li14 {        public static void main(String[] args) {             String string="hello 123 hello";             String rex="(\\w+)\\s+(\\d+)\\s+(\\1)";             Pattern pattern=Pattern.compile(rex);             Matcher matcher=pattern.matcher(string);             if(matcher.find()){                 System.out.println("匹配成功");                 System.out.println("匹配编号0的匹配字符:["+matcher.group(0)+"]");                 System.out.println("匹配编号1的匹配字符:["+matcher.group(1)+"]");                 System.out.println("匹配编号2的匹配字符:["+matcher.group(2)+"]");                 System.out.println("匹配编号3的匹配字符:["+matcher.group(3)+"]");             }        }}
匹配编号0的匹配字符:[hello 123 hello]匹配编号1的匹配字符:[hello]匹配编号2的匹配字符:[123]匹配编号3的匹配字符:[hello]

例子2

import java.util.regex.Matcher;import java.util.regex.Pattern;public class li14 {        public static void main(String[] args) {             String string="hello 123 hello";             String rex="(\\w+)\\s+(\\d+)\\s+\\1";             Pattern pattern=Pattern.compile(rex);             Matcher matcher=pattern.matcher(string);             if(matcher.find()){                 System.out.println("匹配成功");                 System.out.println("匹配编号0的匹配字符:["+matcher.group(0)+"]");                 System.out.println("匹配编号1的匹配字符:["+matcher.group(1)+"]");                 System.out.println("匹配编号2的匹配字符:["+matcher.group(2)+"]");                // System.out.println("匹配编号3的匹配字符:["+matcher.group(3)+"]");    //如果把编号3放开就会报越界异常             }        }}

运行结果:

匹配成功匹配编号0的匹配字符:[hello 123 hello]匹配编号1的匹配字符:[hello]匹配编号2的匹配字符:[123]

在上面这两个例子中,例子1的”//1”外面多加了括号所以,就多了捕获分组,并且保存了捕获分组结果。
然而加这个括号往往是多余的。因为//1已经可以正确表示第一个捕获分组的结果了。就不需要再多加个括号。

然而想要多加个括号也可以:
看例子:

import java.util.regex.Matcher;import java.util.regex.Pattern;public class li14 {        public static void main(String[] args) {             String string="hello 123 hello";             String rex="(\\w+)\\s+(\\d+)\\s+(?:\\1)";             Pattern pattern=Pattern.compile(rex);             Matcher matcher=pattern.matcher(string);             if(matcher.find()){                 System.out.println("匹配成功");                 System.out.println("匹配编号0的匹配字符:["+matcher.group(0)+"]");                 System.out.println("匹配编号1的匹配字符:["+matcher.group(1)+"]");                 System.out.println("匹配编号2的匹配字符:["+matcher.group(2)+"]");                // System.out.println("匹配编号3的匹配字符:["+matcher.group(3)+"]");//同样如果把编号3放开就会报越界异常             }        }}

运行结果:

匹配成功匹配编号0的匹配字符:[hello 123 hello]匹配编号1的匹配字符:[hello]匹配编号2的匹配字符:[123]

总结,不用的括号一定要去掉,否者影响正则的匹配效率,因为括号会保存捕获分组,这样不仅耗费内存也耗费时间。

1 0