【问题标题】:Use previous backreference as name of named capture group使用先前的反向引用作为命名捕获组的名称
【发布时间】:2018-02-15 21:41:18
【问题描述】:

有没有办法使用对前一个捕获组的反向引用作为命名捕获组的名称?这可能是不可能的,如果不是,那么这是一个有效的答案。

以下内容:

$data = 'description: some description';
preg_match("/([^:]+): (.*)/", $data, $matches);
print_r($matches);

产量:

(
    [0] => description: some description
    [1] => description
    [2] => some description
)

我尝试使用对第一个捕获组的反向引用作为命名捕获组 (?<$1>.*) 告诉我这是不可能的,或者我只是没有正确执行:

preg_match("/([^:]+): (?<$1>.*)/", $data, $matches);

产量:

警告:preg_match(): 编译失败: (? 之后的字符无法识别

期望的结果是:

(
    [0] => description: some description
    [1] => description
    [description] => some description
)

这使用preg_match 进行了简化。使用preg_match_all时我通常使用:

$matches = array_combine($matches[1], $matches[2]);

但我想我可能比那更狡猾。

【问题讨论】:

    标签: php regex pcre regex-group backreference


    【解决方案1】:

    简而言之,这是不可能的,你可以坚持你目前一直在使用的编程方式。

    组名(应该是consist of up to 32 alphanumeric characters and underscores, but must start with a non-digit)在编译时被解析,反向引用值只在运行时知道。请注意,这也是您不能在后向引用中使用反向引用的一个原因(虽然您清楚地看到 /(x)y[a-z](?&lt;!\1)/ 是可以的,但 PCRE regex engine sees otherwise 因为它无法通过反向引用推断后向引用的长度)。

    【讨论】:

      【解决方案2】:

      您已经有了正则表达式问题的答案(否),但是对于基于 PHP 的不同方法,您可以尝试使用回调。

      preg_replace_callback($pattern, function($match) use (&$matches) {
          $matches[$match[1]] = $match[2];
      }, $data);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-29
        • 2021-06-26
        • 2014-09-08
        • 1970-01-01
        • 1970-01-01
        • 2016-06-20
        相关资源
        最近更新 更多