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

Good day Bros. I am processing email sender fields, some of which have an email address embedded in a set of parentheses following a string inside another set of parentheses. I need a regexp that will get only the former, leaving the latter with the sender name. To be clear, in the following example:
#!/usr/bin/perl -w use strict; my $sentto = 'Fred Flintstone (US) (fredf@gmail.com)'; $sentto =~ m/\(.+?@.+?\)/; print "First: $`\nSecond: $&"
I would like $` to contain "Fred Flintstone (US) " and $& to contain "(fredf@gmail.com)". The regexp I have in there puts " (US) " at the beginning of $&. I understand why this happens, but not how to fix it. I thought about maybe a look-back assertion for a close-paren, but I have some addresses like "Barney Rubble (barneyr@gmail.com)" so I don't think that will work. I'd like to have a regexp that will pick off the parenthetical address for both kinds of senders. Can someone suggest a solution?
"I think computers have complicated lives very bigly. The whole age of, you know, computer has made it where nobody knows exactly what's going on." --D. Trump

Replies are listed 'Best First'.
Re: Need regexp to pick off second parenthetical item
by AnomalousMonk (Archbishop) on Mar 26, 2017 at 01:03 UTC

    c:\@Work\Perl\monks>perl -wMstrict -le "my $sentto = 'Fred Flintstone (US) (fredf@gmail.com)'; ;; my $captured = my ($first, $second) = $sentto =~ m{ \A (.*) \s+ ([(] [^(]* [)]) \z }xms; ;; if ($captured) { print qq{first '$first' second '$second'}; } else { warn 'parse failed'; } " first 'Fred Flintstone (US)' second '(fredf@gmail.com)'
    (I don't like using  $& and friends.) (Update: Also, the regex assumes the second parenthetic group has no nested parentheses!)


    Give a man a fish:  <%-{-{-{-<

Re: Need regexp to pick off second parenthetical item
by tybalt89 (Monsignor) on Mar 26, 2017 at 01:05 UTC
    #!/usr/bin/perl # http://perlmonks.org/?node_id=1185969 use strict; use warnings; my $sentto = 'Fred Flintstone (US) (fredf@gmail.com)'; $sentto =~ m/.+\K\(.*/; print "First: $`\nSecond: $&\n"
      Awesome. I didn't know about \K.

        Regex operator  \K is only available from Perl version 5.10 onward.


        Give a man a fish:  <%-{-{-{-<