使用先前的反向引用作为命名捕获组的名称 [英] Use previous backreference as name of named capture group

查看:53
本文介绍了使用先前的反向引用作为命名捕获组的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

以下内容:

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

产量:

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

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

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:

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

产量:

警告:preg_match(): 编译失败:(?< at offset 12

Warning: preg_match(): Compilation failed: unrecognized character after (?< at offset 12

想要的结果是:

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

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

This is simplified using preg_match. When using preg_match_all I normally use:

$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.

组名称(应该由最多 32 个字母数字组成字符和下划线,但必须以非数字开头)在编译时解析,并且反向引用值仅在运行时已知.请注意,这也是您不能在后视中使用反向引用的原因(尽管您清楚地看到 /(x)y[az](?<!\1)/ 是可以的,PCRE 正则表达式引擎另有看法,因为它无法通过反向引用推断后视的长度).

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. Note it is also a reason why you cannot use a backreference inside a lookbehind (altghough you clearly see that /(x)y[a-z](?<!\1)/ is OK, the PCRE regex engine sees otherwise as it cannot infer the length of the lookbehind with a backreference).

这篇关于使用先前的反向引用作为命名捕获组的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆