bangor has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I am trying to write a regex that will capture a mail id from a sendmail log file line. When there are a big number of multiple recipients their ids are listed over multiple lines and a number is added to the id:
# normal line w7R9Kstc017510: split: # split lines w7R9Kstc017510[1]: split: w7R9Kstc017510[2]: split:
The regex needs to capture both variations - this is what I tried:
/(\w+)(?:\[\d+\]): split:/
But that doesn't capture the normal line.

Replies are listed 'Best First'.
Re: Help with regex
by 1nickt (Canon) on Sep 04, 2018 at 23:01 UTC

    Hi, you need to make the optional part optional:

    perl -Mstrict -wlE ' my @str=("w7R9Kstc017510: split:","w7R9Kstc017510[1]: split:","w7R9Kst +c017510[2]: split:"); for (@str) { say "$_ matches" if /(\w+)(?:\[\d+\])?: split:/ # here ^ } ' w7R9Kstc017510: split: matches w7R9Kstc017510[1]: split: matches w7R9Kstc017510[2]: split: matches
    Hope this helps!


    The way forward always starts with a minimal test.
      Thanks 1nickt, that works perfectly.