开发者

Perl iterate through each match

Let's say I'm scanning through a page of raw html looking for this rege开发者_运维百科x. (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?


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.


The global matching 'g' modifier returns a list of captured matches in list context:

say $_ for $str =~ /un($wanted)/g;    # Prints only $wanted


@Zaid: I think your approach is more compact. hope the following snippet will help to understand your example

my $str = 'file_%date%_%name%_%lang%.txt';
my @ts = $str =~ /%([\w]+)%/g;#           <----------Zaid said
print join(", ", @ts);

Output:

date, name, lang
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜