gpt4 book ai didi

perl - perl 正则表达式中捕获组的最大数量

转载 作者:行者123 更新时间:2023-12-04 02:51:24 24 4
gpt4 key购买 nike

给定 perl 中的正则表达式,我如何找到该正则表达式中捕获组的最大数量?我知道我可以使用 $1、$2 等来引用第一、第二等捕获的组。但是如何找到此类组的最大数量?通过捕获的组,我的意思是括号中的正则表达式匹配的字符串。例如:如果正则表达式是 (a+)(b+)c+,则字符串“abc”匹配该正则表达式。第一个捕获的组将是 $1,第二个将是 $2。

最佳答案

amon 在提到 %+ 散列时暗示了这个问题的答案。但是你需要的是 @+数组:

@+

This array holds the offsets of the ends of the last successful submatches in the currently active dynamic scope. $+[0] is the offset into the string of the end of the entire match. This is the same value as what the pos function returns when called on the variable that was matched against. The nth element of this array holds the offset of the nth submatch, so $+1 is the offset past where $1 ends, $+[2] the offset past where $2 ends, and so on. You can use $#+ to determine how many subgroups were in the last successful match. See the examples given for the @- variable. [enphasis added]

$re = "(.)" x 500;
$str = "a" x 500;
$str =~ /$re/;
print "Num captures is $#+"; # outputs "Num captures is 500"

关于perl - perl 正则表达式中捕获组的最大数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17582220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com