in reply to Regex substitute matches second match first?

You're being too greedy. Change:

$line =~ s/.*\]: //;

...to:

$line =~ s/.*?\]: //; # note the ? following .*

That'll stop as soon as it sees the first ], whereas without the non-greedy quantifier ?, it'll slurp in the entire string until it finds the last ]

Here's a way that you can do all of your matching and capture the IP on one line:

if ($line =~ /\[(\d+\.\d+\.\d+\.\d+)\].*Relay access denied/) { my $ip = $1; print "$ip\n"; }

Replies are listed 'Best First'.
Re^2: Regex substitute matches second match first?
by Marshall (Canon) on May 25, 2016 at 18:02 UTC
    As a minor nit, you can do away with this $1 stuff and assign directly to $ip like this:
    if (my ($ip) = $line =~ /\[(\d+\.\d+\.\d+\.\d+)\].*Relay access denie +d/) { print "$ip\n"; }
Re^2: Regex substitute matches second match first?
by Linicks (Scribe) on May 25, 2016 at 19:08 UTC

    Actually, this has made me think now I understand what is going on.

    Postfix logs the mavericks between [] brackets. The first set of [] brackets are the session ID. There is only the session ID [] brackets and the maverick's [] brackets on the matches I need to check.

    So all I need to do for ALL the matches is:

    $line =~ /.*[//; gobble all up to the last [ $line =~ /].*//; get rid of the rest after ]

    Thanks!

    Nick

Re^2: Regex substitute matches second match first?
by Linicks (Scribe) on May 25, 2016 at 17:18 UTC

    Heh, blimey, thank you. So /g sometimes isn't needed - I have read about 'greedy' regex before but never encountered it.

    Many thanks for your wisdom!

    Nick

      The /g modifier is for global matches. For instance, if you had numerous IPs on a single line, and you wanted to grab them all. eg: (untested)

      my $line = "1.1.1.1 blah 2.2.2.2"; my @ips = $line =~ /\d+\.\d+\.\d+\.\d+/g;

      Now $ips[0] would be '1.1.1.1' and $ips[1] would contain '2.2.2.2'.

      A couple of docs you can review are perlretut and perlre.

        Thanks for your help, will read up

        Nick