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

转载于:http://www.jb51.cc/article/p-ojixyucg-bqm.html

前言:

本篇文章主要为了强调正则中\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]

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

相关文章

正则替换html代码中img标签的src值在开发富文本信息在移动端...
正则表达式
AWK是一种处理文本文件的语言,是一个强大的文件分析工具。它...
正则表达式是特殊的字符序列,利用事先定义好的特定字符以及...
Python界一名小学生,热心分享编程学习。
收集整理每周优质开发者内容,包括、、等方面。每周五定期发...