Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

regex

perl

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 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.

like image 930
cskwrd Avatar asked Feb 21 '10 02:02

cskwrd


People also ask

Does regex match return array?

match(regexp) finds matches for regexp in the string str . If the regexp has flag g , then it returns an array of all matches as strings, without capturing groups and other details. If there are no matches, no matter if there's flag g or not, null is returned.

What is the meaning of $1 in Perl regex?

$1 equals the text " brown ".

What does capture mean in regex?

capturing in regexps means indicating that you're interested not only in matching (which is finding strings of characters that match your regular expression), but you're also interested in using specific parts of the matched string later on.


1 Answers

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 
like image 147
friedo Avatar answered Nov 11 '22 23:11

friedo