in reply to Re: Re: Regex isn't performing like I think it should
in thread Regex isn't performing like I think it should

What you're running into here is a matter of context. You're evaluating the regex in scalar context, which, when used with the /g modifier, performs a progressive match. This means that every time that regex is evaluated, it starts trying to match immediately after the previous. In other words, it keeps track of it's position in the string and starts where it left off.

One solution to this is to use a while loop to take advantage of the progressive matching (every time the /g regex is eval'd you get the next values for $1 and $2) as jmarshall99 did. The other is to evaluate your regex in list context to rip out all the matches at once.

my $string = '<a href="page.cfm?objectid=11933900&method=full&siteid=5 +0144"> Costly false alarms </a> <a href="page.cfm?objectid=11933890&m +ethod=full&siteid=50144"> Mindless yobs terrorise OAPs </a> <a href=" +page.cfm?objectid=11933879&method=full&siteid=50144"> Road deaths </a +> <a href="page.cfm?objectid=11933842&method=full&siteid=50144"> Twis +ted porn pervert caged for life </a> <a href="page.cfm?objectid=11933 +800&method=full&siteid=50144"> Greenbelt homes plan appeal thrown out + </a>'; my @matches = $string =~ m!(<a[^>]*>)(.+?</a[^>]*>)!ig; print "$_\n" foreach @matches;
Or even using a hash (as long as your a tags don't repeat)...
my %matches = $string =~ m!(<a[^>]*>)(.+?</a[^>]*>)!ig; foreach my $key (keys %matches) { print "$key\n"; print "$matches{$key}\n\n"; }

-Bird

Replies are listed 'Best First'.
Re: Re: Re: Re: Regex isn't performing like I think it should
by Popcorn Dave (Abbot) on Jun 12, 2002 at 22:21 UTC
    ++ for that!!!

    I'd never even thought of, or even seen for that matter, using the array to grab all matches. Excellent technique!

    As far as using a hash, that's actually what it's going in to just for that very reason - to eliminate dups. The problem is, with this particular HTML, there are duplicate links with the news headline as one link, the associated text, then 'more' as a duplicate link underneath the associated text.

    Again, ++ ++ for that array idea! Thanks!

    Some people fall from grace. I prefer a running start...