如何在 Perl 中找到正则表达式匹配的位置? [英] How can I find the location of a regex match in Perl?

查看:88
本文介绍了如何在 Perl 中找到正则表达式匹配的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个接收字符串和正则表达式的函数.我需要检查是否有匹配项并返回匹配项的开始和结束位置.(正则表达式已经由 qr// 编译.)

I need to write a function that receives a string and a regex. I need to check if there is a match and return the start and end location of a match. (The regex was already compiled by qr//.)

该函数可能还会收到一个全局"标志,然后我需要返回所有匹配项的 (start,end) 对.

The function might also receive a "global" flag and then I need to return the (start,end) pairs of all the matches.

我无法更改正则表达式,甚至不会在其周围添加 (),因为用户可能会使用 ()\1.也许我可以使用 (?:).

I cannot change the regex, not even add () around it as the user might use () and \1. Maybe I can use (?:).

示例:给定ababab"和正则表达式 qr/ab/,在全局情况下,我需要取回 3 对 (start, end).

Example: given "ababab" and the regex qr/ab/, in the global case I need to get back 3 pairs of (start, end).

推荐答案

内置变量 @-@+ 分别保存开始和结束位置,上一次成功的比赛.$-[0]$+[0] 对应整个模式,而 $-[N]$+[N] 对应于 $N($1$2 等)子匹配项.

The built-in variables @- and @+ hold the start and end positions, respectively, of the last successful match. $-[0] and $+[0] correspond to entire pattern, while $-[N] and $+[N] correspond to the $N ($1, $2, etc.) submatches.

这篇关于如何在 Perl 中找到正则表达式匹配的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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