Or if you want to grab all the matches in an array you can:
use strict; use warnings; my $text = "test1 zzzzzzzzzzzzzzz test2 test3 test4 test5 zzzzzzzzzzzz +zzz test6 test7 zzzzzzzzzzzzzzz test8 test9 test10"; my @matches = $text =~ /([a-zA-Z0-9]+\s+[z]{15}\s+[a-z0-9]+)/g; print "string: $_!\n" for @matches;
Prints:
string: test1 zzzzzzzzzzzzzzz test2! string: test5 zzzzzzzzzzzzzzz test6! string: test7 zzzzzzzzzzzzzzz test8!
Note that in this case the regex is evaluated in list context so it generates the list of captures as the result. bobf's version evaluates the regex in scalar context and generates a success/fail result and (because of the /g switch) stops on successive matches until all matches are found. Note that bobf's version retreives the capture text from the capture variable ($1 in this case) whereas the list version gets the captures put into the list. Consider:
... my @cap = $text =~ /([a-zA-Z0-9]+)\s+[z]{15}\s+([a-z0-9]+)/g; while (@cap) { print "string: $cap[0] ... $cap[1]\n"; splice @cap, 0, 2; }
which prints:
string: test1 ... test2 string: test5 ... test6 string: test7 ... test8
Note the two capture groups in the regex now. To generate the output shown in this case bobf's print line would become:
print "string: $1 ... $2\n";
In reply to Re: regex question
by GrandFather
in thread regex question
by goff
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |