in reply to Regex substitute matches second match first?

Hi Nick,

I believe what's going on is this, from perlre:

By default, a quantified subpattern is "greedy", that is, it will match as many times as possible (given a particular starting location) while still allowing the rest of the pattern to match. If you want it to match the minimum number of times possible, follow the quantifier with a ?.

This works for me: $line =~ s/.*?\]: //;

And although not necessary in this case, I personally prefer to be a little more explicit and I'd anchor the match: $line =~ s/^.*?\]: //;

But I'm wondering, if you're just trying to match the IP address enclosed in those brackets, why not do something like what stevieb suggested - or, taking it even further (depending on personal taste this may be a bit overkill):

use Regexp::Common qw/net/; if ($line =~ /Relay access denied/) { my @ips = $line=~/$RE{net}{IPv4}/g; print "$_\n" for @ips; }

Hope this helps,
-- Hauke D

Replies are listed 'Best First'.
Re^2: Regex substitute matches second match first?
by Anonymous Monk on May 25, 2016 at 17:30 UTC

    Hi Hauke D

    Thanks for the reply

    OK, the code:

    use Regexp::Common qw/net/; if ($line =~ /Relay access denied/) { my @ips = $line=~/$RE{net}{IPv4}/g; print "$_\n" for @ips; }

    looks good, but the example I used is not the only scenerio - I capture several matches all covered but one regex - and other lines contain certain IP's that I am not interested in - postfix always puts the maverick ip in [] brackets.

    Thanks for your help - I will look at this further anyway.

    Nick>