Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl iterate through each match

Tags:

regex

perl

Let's say I'm scanning through a page of raw html looking for this regex. (The quote mark on the end is intentional).

m/(https?:\/\/.*?(?:'|"))/ 

This pattern is likely to match ~ 100 times. What is a common perl idiom/a quick way to iterate through a list of all capture group matches?

like image 261
providence Avatar asked Sep 28 '11 08:09

providence


1 Answers

From the perlretut (a very fine tutorial)

while ($x =~ /(\w+)/g) {         print "Word is $1, ends at position ", pos $x, "\n";     } 

You can use while together with the g modifier to iterate over all matches, with $1 you get the content of your capturing group 1, and in this example from the tutorial you get also the position with pos.

like image 162
stema Avatar answered Sep 19 '22 13:09

stema