PHP 中的命名正则表达式反向引用

Named regular expression back reference in PHP

使用 PHP 5.5+ 正则表达式,我想使用命名反向引用来捕获一个组。

例如,我想要匹配以下文本:

1-1
2-2

但不是以下

8-7

但是,当我尝试使用反向引用时,PHP 将其标记为找到的匹配项:

/* This statement evaluates to 1 */
preg_match("/(?<one>[1-9])\-(?<two>\g<one>)/", "8-7");

除了使用编号引用之外,是否有解决此问题的方法?

请参阅 PCRE documentation 中的这段摘录:

For compatibility with Oniguruma, the non-Perl syntax \g followed by a name or a number enclosed either in angle brackets or single quotes, is an alternative syntax for referencing a subpattern as a subroutine, possibly recursively.

Note that \g{...} (Perl syntax) and \g<...> (Oniguruma syntax) are not synonymous. The former is a back reference; the latter is a subroutine call.

通过使用\g<one>,你不引用匹配,而是引用子模式,参见regex101.com的解释。

\g<one> recurses the subpattern named one

您需要使用 </code> 才能实际匹配第一组中捕获的相同文本。</p> <pre><code>(?<one>[1-9])\-(?<two>)

或者(对实际文本的命名反向引用),

(?<one>[1-9])\-(?<two>\g{one})

matches the same text as most recently matched by the 1st capturing group

参见 a numbered demo and a named back-reference demo