in reply to Help with pattern matching

my $line = 'Oct 9 08:50:53 mail_server sendmail[30172]: j99FopoN03017 +2: from=<support@symantec.com>, size=0, class=0, nrcpts=0, proto=ESMT +P, daemon=MTA, relay=[218.1.114.182]'; if ($line =~ /relay=\[(.*?)\]/) { print $1; }

Replies are listed 'Best First'.
Re^2: Help with pattern matching
by mhearse (Chaplain) on Oct 09, 2005 at 23:53 UTC
    That does work, but I need the bracket match to be optional, so that I can match something like this:
    Oct 9 04:20:35 mail_server sendmail[20773]: j975sOqf032312: to=<522-2 +204194-1-13-51954mpxas@dimexpress.com>, delay=2+05:26:11, xdelay=00:0 +0:00, mailer=esmtp, pri=19293815, relay=mail.xpress.com.
      my $line1 = 'Oct 9 08:50:53 mail_server sendmail[30172]: j99FopoN0301 +72: from=<support@symantec.com>, size=0, class=0, nrcpts=0, proto=ESM +TP, daemon=MTA, relay=[218.1.114.182]'; my $line2 = 'Oct 9 04:20:35 mail_server sendmail[20773]: j975sOqf0323 +12: to=<522-2204194-1-13-51954mpxas@dimexpress.com>, delay=2+05:26:11 +, xdelay=00:00:00, mailer=esmtp, pri=19293815, relay=mail.xpress.com' +; if ($line1 =~ /relay=\[?(.*?)\]?$/) { print $1, "\n"; } if ($line2 =~ /relay=\[?(.*?)\]?$/) { print $1, "\n"; }

      This prints:

      218.1.114.182 mail.xpress.com

      Ah. And it didn’t occur to you that people would need example data that shows all the possible scenarios to be able to solve your problem? :-)

      Is the relay= bit always the last part of the line? In that case you could just use

      m{ relay= \[? (.*) \]? }msx

      If not, then it is probably followed by a comma or end of line (again, can’t know without more sample data), so what you need is

      m{ relay= \[? (.*?) \]? (:? \Z | , ) }msx

      Note that while I’m using a lazy quantifier in the second case (which is what is causing the problems in your patterns), it is followed by a non-optional part of the regex, so it will always be forced to consume as much as necessary to make the overall pattern match.

      Makeshifts last the longest.