我怎么能存储的正则表达式捕获Perl中的数组? [英] How can I store regex captures in an array in Perl?
问题描述
我想在Perl中使用正则表达式。我是什么奇怪了,如果它可以将所有的前pression匹配存储到一个数组中?我知道我可以使用以下命令:($ 1,...,$ N)= M / EXPR /克;
,但它好像只能如果你使用知道你正在寻找匹配的数量。我曾尝试我@array = M / EXPR /克;
,但似乎并没有工作。
I'm trying to use regex in Perl. What I was wonder was if it is possible to store all matches to the expression into an array? I know I can use the following: ($1,...,$n) = m/expr/g;
but it seems as though that can only be used if you know the number of matches you are looking for. I have tried my @array = m/expr/g;
but that doesn't seem to work.
感谢您的帮助!
推荐答案
如果你正在做一个全球性的匹配( / G
),然后在列表上下文正则表达式将返回所有拍摄比赛。简单地做:
If you're doing a global match (/g
) then the regex in list context will return all of the captured matches. Simply do:
my @matches = ( $str =~ /pa(tt)ern/g )
此命令,例如:
perl -le '@m = ( "foo12gfd2bgbg654" =~ /(\d+)/g ); print for @m'
给出的输出:
12
2
654
这篇关于我怎么能存储的正则表达式捕获Perl中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!