简体   繁体   English

使用先前的反向引用作为命名捕获组的名称

[英]Use previous backreference as name of named capture group

Is there a way to use a backreference to a previous capture group as the name of a named capture group ? 有没有办法使用对先前捕获组的反向引用作为命名捕获组的名称? This may not be possible, if not, then that is a valid answer. 这可能是不可能的,如果没有,那么这是一个有效的答案。

The following: 下列:

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

Yields: 产量:

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

My attempt using a backreference to the first capture group as a named capture group (?<$1>.*) tells me it's either not possible or I'm just not doing it correctly: 我尝试使用第一个捕获组的反向引用作为命名捕获组(?<$1>.*)告诉我它不可能或者我只是没有正确执行它:

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

Yields: 产量:

Warning: preg_match(): Compilation failed: unrecognized character after (?< at offset 12 警告:preg_match():编译失败:无法识别的字符(?<在偏移量12处

The desired result would be: 期望的结果是:

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

This is simplified using preg_match . 使用preg_match简化了这一过程。 When using preg_match_all I normally use: 使用preg_match_all我通常使用:

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

But thought I might be slicker than that. 但我想我可能比那更光滑。

In short, it is not possible, you can stick to the programming means you have been using so far. 简而言之,这是不可能的,你可以坚持到目前为止你一直在使用的编程方式。

Group names (that should consist of up to 32 alphanumeric characters and underscores, but must start with a non-digit ) are parsed at compile time, and a backreference value is only known at run-time. 组名称(应包含最多32个字母数字字符和下划线,但必须以非数字开头 )在编译时进行解析,并且反向引用值仅在运行时已知。 Note it is also a reason why you cannot use a backreference inside a lookbehind (altghough you clearly see that /(x)y[az](?<!\\1)/ is OK, the PCRE regex engine sees otherwise as it cannot infer the length of the lookbehind with a backreference). 请注意,这也是为什么你不能在lookbehind中使用反向引用的原因(尽管你清楚地看到/(x)y[az](?<!\\1)/是正常的, PCRE正则表达式引擎看不到,因为它无法推断带有反向引用的后视长度)。

You already have an answer to the regex question (no), but for a different PHP based approach you could try using a callback. 您已经有了正则表达式问题的答案(否),但对于不同的基于PHP的方法,您可以尝试使用回调。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM