How can I store regex captures in an array in Perl?

后端 未结 7 1213
孤城傲影
孤城傲影 2020-12-01 03:38

Is it possible to store all matches for a regular expression into an array?

I know I can use ($1,...,$n) = m/expr/g;, but it seems as though that can on

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 03:45

    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 )
    

    This command for example:

    perl -le '@m = ( "foo12gfd2bgbg654" =~ /(\d+)/g ); print for @m'
    

    Gives the output:

    12
    2
    654
    

提交回复
热议问题