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

If I have a string which contains this: $string = 'To: <someemail@somedomain.tld>'; How can I strip off everything except the email address?

Or if It was something like this: $string = 'To: someemail@somedomain.tld'; And I have no way of knowing if it has more or not. If I knew it contained only the latter example, I could just split it by the blank space between the : and the some...

It might even contain more than that, such as $string = 'To: You and I <somemail@somedomain.tld>'; Or the like.

Is there a simple way of getting rid of everything EXCEPT the email address?

thx,
Richard

Replies are listed 'Best First'.
Re: Strip everything but an email address
by dominix (Deacon) on Feb 14, 2004 at 05:24 UTC
    "everything EXCEPT" is too huge to describe so your question is actually, "How do I match an email adresse, then I can drop the rest". and it have been often asked over here. an the usual response is use Email::Valid. in your case if you want to rely on a regex look at this example from Mastering regular expression
    anyway keep in mind : what should you match here ? q/to: "me@me.fr" <to@to.pf> /
    --
    dominix
Re: Strip everything but an email address
by bart (Canon) on Feb 14, 2004 at 09:27 UTC
    I use Mail::Address from MailTools for this.
    use Mail::Address; my $string = 'To: someone <someemail@somedomain.tld>, "someone else" < +someoneelse@some.other.domain>, info@somewhere.com (info address)'; my @address = map $_->address, Mail::Address->parse($string); { local $\ = "\n"; print for @address; }
    Result:
    someemail@somedomain.tld
    someoneelse@some.other.domain
    info@somewhere.com
    
Re: Strip everything but an email address
by Anonymous Monk on Feb 14, 2004 at 05:17 UTC

    my @emails = ( 'To: <firstone@somewhere.com>', 'To: You and I <secondone@somewhere.com>', 'To: thirdone@somewhere.com' ); for (@emails) { /^To:\s*[^<]*<([^>]+)>/ || /^To:\s*(.+)$/; print $1, $/; }