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

I am new to regex, and I need a regex to return the domain name from an email address stored in a string, for example
my $email = "fake@email.com"; my $domain = ......?
Any help would be much appreciated. Cheers.

Edit kudra, 2002-08-30 Changed title

Replies are listed 'Best First'.
Re: (nrd)Regex Help
by newrisedesigns (Curate) on Aug 29, 2002 at 05:04 UTC

    See this node for some answers to your problem.

    A quick solution, however, would be to /\@(.+?)\s/; or ($user, $domain) = split(/\@/, $email, 2);

    Update: Fixed a yet another typo, got rid of a temp array... thanks grep :)

    John J Reiser
    newrisedesigns.com

      /\@(.+?)\s/;

      That wouldn't match his example, "fake@email.com" due to the \s and the fact that his example has no whitespace. You also don't need to escape the @.

      This:

      /@(.*)/
      would work.

      Note that, without anchoring the end of it, you must .* rather than .*? because the latter can (and would) match nothing (i.e. an empty match) and end.

      Of course, I agree that you shouldn't use a regex for this anyway so caveats, disclaimers, etc. :-)

      -sauoq
      "My two cents aren't worth a dime.";
      

        Very true.

        I assumed he'd be pulling the addresses out of a text file (or HTML) and now that I think about it, (") would be a better ending boundary for HTML.

        D'oh. You know what they say when you assume... : /

        John J Reiser
        newrisedesigns.com

Re: Regex Help
by grep (Monsignor) on Aug 29, 2002 at 05:41 UTC
    As newrisedesigns points out - you should use Mail::Address which is in MailTools. If you are unsure why you should use that module instead of a regex read RFC 821. This explains all the valid email address styles and how to parse them :)

    grep
    Mynd you, mønk bites Kan be pretti nasti...