Java正则表达式之反向引用(Backreferences)

来源:互联网 发布:php开源博客 编辑:程序博客网 时间:2024/06/12 00:28
反向引用(Backreferences)是Java正则表达式的重要特性。

为了理解反向引用,我们先对解释Java正则表达式里面的组。组在正则表达式中意味着将多个字符作为一个单独的单元,通过将字符放在()中,每个()代表一个组。每一组都有一个行号,从1开始。Matcher类的groupCount方法返回模式(pattern)关联Matcher实例组的个数。第0组指向整个表达式。


例子:
    String regex = "\\b(\\d{3})(\\d{3})(\\d{4})\\b";    Pattern p = Pattern.compile(regex);    String source = "1234567890, 12345,  and  9876543210";    Matcher m = p.matcher(source);    while (m.find()) {      System.out.println("Phone: " + m.group() + ", Formatted Phone:  ("          + m.group(1) + ") " + m.group(2) + "-" + m.group(3));    }
注:\b表示只匹配在单词边界的10个数字。
运行结果:
Phone:1234567890,Formatted Phone:(123)456-7890
Phone:9876543210,Formatted Phone:(977)654-3210

也可以通过正则替换完成:    
    String regex = "\\b(\\d{3})(\\d{3})(\\d{4})\\b";    String replacementText = "($1) $2-$3";    String source = "1234567890, 12345, and 9876543210";    Pattern p = Pattern.compile(regex);    Matcher m = p.matcher(source);    String formattedSource = m.replaceAll(replacementText);

反向引用非常方便,因为它允许重复一个模式(pattern),无需再重写一遍。我们可以使用\#(#是组号)来引用前面已定义的组。比如一个文本以abc开始,接着为xyz,紧跟着abc,对应的正则表达式可以为“abcxyzabc”,也可以使用反向引用重写正则表达式,“"(abc)xyz\1"”,\1表示第一组(abc)。\2表示第二组,\3表示第三组,以此类推。
使用反向引用匹配2-5个字母的回文(palindromes)。
例子:
\b(\w)?(\w)\w?\2\1

my dad sees a kayak at noon

(\w)a\1
hah dad bad dab gag gab


参考资料:

RegExrv 2.0

0 0