如何访问正则表达式子程序中的捕获组? [英] How to access the capture group in a regex subroutine?

查看:46
本文介绍了如何访问正则表达式子程序中的捕获组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我想在几个地方使用的模式,但我想访问该模式的内部部分.有没有办法做到这一点?

I have a pattern that I want to use in a couple of places, but I want access to an inner part of the pattern. Is there a way to do this?

在这个简化示例中:

(?(DEFINE)
    (?<_isa_> \s+ (?<isa> is \s+ a) \s+ )
)
this (?&_isa_) (?<test>test)

我想在正则表达式成功时访问命名组 isa 中匹配的捕获字符串,而不必像这样拉出周围的 \s+:

I'd like to have access to the matched captured string in the named group isa when the regex succeeds, without having to pull out the surrounding \s+ like so:

(?(DEFINE)
    (?<_isa_> is \s+ a )
)
this \s+ (?<isa>(?&_isa_)) \s+ (?<test>test)

因为,这基本上意味着每次我想在实际的正则表达式中执行此操作时,我都必须指定预子匹配、子匹配和后子匹配,这不是我想要的.

Because, this would basically mean that I have to specify a pre-submatch, submatch and post-submatch every time I want to do this in my actual regex, which is not what I want.

推荐答案

这是不可能的,因为 DEFINE 块内的捕获组仅在该块内可见",不能从模式.

It is not possible, as the capture groups inside a DEFINE block are only "visible" inside that block and cannot be accessed from the pattern.

请参阅此 perlre 参考:

See this perlre reference:

这允许我们定义仅由递归机制执行的子模式... 注意递归返回后无法访问在递归内部匹配的捕获组,因此捕获组的额外层是必要的....最后,请记住,在 DEFINE 块内创建的子模式计入捕获的绝对和相对数量.

This allows one to define subpatterns which will be executed only by the recursion mechanism... Note that capture groups matched inside of recursion are not accessible after the recursion returns, so the extra layer of capturing groups is necessary. ... Finally, keep in mind that subpatterns created inside a DEFINE block count towards the absolute and relative number of captures.

因此,即使您有 3 个命名的捕获组,您也只能访问在主模式中定义的 test 组.

So, even though you have 3 named capture groups, you can only access test group that was defined in the main pattern.

这篇关于如何访问正则表达式子程序中的捕获组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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