为什么反向引用捕获组适用于 Java 中的多位数字?

Why does backreferencing capturing groups work for multiple digit numbers in Java?

假设您有一个字符串:

String string = "ab #1?AZa$ab #1?AZa$"

您正在尝试验证第十个字符是否为非空白字符,以及第二十个字符是否与第十个字符相同。此外,第1和第11、第2和第12、第3和第13等都有相应的验证,每个都有自己不同的要求(完整列表是here),所以你必须使用10个捕获组。我发现以下正则表达式仍然可以验证上述字符串:

string.matches("^([a-z])(\w)(\s)(\W)(\d)(\D)([A-Z])([a-zA-Z])([aeiouAEIOU])(\S)\1\2\3\4\5\6\7\8\9\10$") //returns true

我的问题是关于最后的反向引用:

\10

这不应该解释为“匹配第一个字符”,然后“匹配0”(数字)吗?如果不以某种方式将 1 和 0 组合成 10,我看不出这是如何被解释为“与第十个字符匹配”的。令人费解的是,用括号将 1 和 0 括起来是行不通的。

Java 的行为记录在 Pattern:

In this class, through are always interpreted as back references, and a larger number is accepted as a back reference if at least that many subexpressions exist at that point in the regular expression, otherwise the parser will drop digits until the number is smaller or equal to the existing number of groups or it is one digit.