Java 正则表达式中的反向引用
java programming java8object oriented programming
捕获组是一种将多个字符视为单个单元的方法。它们是通过将要分组的字符放在一组括号内来创建的。例如,正则表达式 (dog) 创建一个包含字母"d"、"o"和"g"的组。
捕获组的编号是通过从左到右计算其左括号来计算的。例如,在表达式 ((A)(B(C))) 中,有四个这样的组 -
((A)(B(C))) (A) (B(C)) (C)
示例
反向引用允许使用数字(如 \#,其中 # 是组号)重复捕获组。请参阅以下示例:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Tester { public static void main(String[] args) { //2 followed by 2 five times String test = "222222"; String pattern = "(\d\d\d\d\d)"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(test); if (m.find( )) { System.out.println("Matched!"); }else{ System.out.println("not matched!"); } //\1 as back reference to capturing group (\d) pattern = "(\d)\1{5}"; r = Pattern.compile(pattern); m = r.matcher(test); if (m.find( )) { System.out.println("Matched!"); }else{ System.out.println("not matched!"); } } }