In Perl, how can I use one regex grouping to capture more than one occurrence that matches it, into several array elements?
For example, for a string:
var1=100 var2=90 var5=hello var3="a, b, c" var7=test var3=hello
to process this with code:
$string = "var1=100 var2=90 var5=hello var3=\"a, b, c\" var7=test var3=hello";
my @array = $string =~ <regular expression here>
for ( my $i = 0; $i < scalar( @array ); $i++ )
{
print $i.": ".$array[$i]."\n";
}
I would like to see as output:
0: var1=100
1: var2=90
2: var5=hello
3: var3="a, b, c"
4: var7=test
5: var3=hello
What would I use as a regex?
The commonality between things I want to match here is an assignment string pattern, so something like:
my @array = $string =~ m/(\w+=[\w\"\,\s]+)*/;
Where the * indicates one or more occurrences matching the group.
(I discounted using a split() as some matches contain spaces within themselves (i.e. var3...) and would therefore not give desired results.)
With the above regex, I only get:
0: var1=100 var2
Is it possible in a regex? Or addition code required?
Looked at existing answers already, when searching for "perl regex multiple group" but not enough clues:
- http://stackoverflow.com/questions/3159991/dealing-with-multiple-capture-groups-in-multiple-records
- http://stackoverflow.com/questions/1313332/multiple-matches-within-a-regex-group
- http://stackoverflow.com/questions/3172643/regex-repeated-capturing-groups
- http://stackoverflow.com/questions/446126/regex-match-and-grouping
- http://stackoverflow.com/questions/1407435/how-do-i-regex-match-with-grouping-with-unknown-number-of-groups
- http://stackoverflow.com/questions/1116193/awk-extract-multiple-groups-from-each-line
- http://stackoverflow.com/questions/1791097/matching-multiple-regex-groups-and-removing-them
- http://stackoverflow.com/questions/2685456/perl-deleting-multiple-re-occuring-lines-where-a-certain-criteria-is-met
- http://stackoverflow.com/questions/2398730/regex-matching-into-multiple-groups-per-line
- http://stackoverflow.com/questions/1087720/php-regex-grouping-multiple-matches
- http://stackoverflow.com/questions/3246237/how-to-find-multiple-occurances-with-regex-groups