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

I have a form field where a user can add up to three comma and/or comma space separated email addresses. Can someone help me write a regex s/// to strip out all email addresses that have commas OVER 3?
$email =~ s/\,.+$//gi;
This strips all but the first one out. I need to strip out only those that are over the 3 email address limit. I am totally lost.

Replies are listed 'Best First'.
Re: stripping email address regex
by merlyn (Sage) on Sep 15, 2005 at 19:08 UTC
    Unfortunately, a comma can appear inside an email address within doublequotes or a comment. So you can't just split on commas, or you'll possibly split in the middle of an email address.

    You'll want the parse method of Email::Address to do the job properly.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: stripping email address regex
by saintmike (Vicar) on Sep 15, 2005 at 19:06 UTC
    Using Email::Find is easier than dealing with what can what cannot be part of an email address:
    use Email::Find; my $text = 'foo@bar.com, bar@foo.com, a@b.com, b@a.com, c@d.com'; my @emails = (); find_emails($text, sub { push @emails, $_[1] if @emails < 3 } ); print "@emails\n";
      Hi.

      I am using

      use Email::Find; #$v_email contains a string of emails my @emails = (); find_emails($v_email, sub { push @emails, $_[1] if @emails < 3 } ); $v_email = join(", ",@emails); print "v_email: $v_email\n"
      And it prints out the email addresses right but now it doesn't email them anymore. It appears to be in the correct format of email@address.com, email2@address.com, email3@address.com . I join it back into $v_email to print MAIL "To: $v_email";

      Any idea why it used to email but now that this is added, it doesn't?

Re: stripping email address regex
by socketdave (Curate) on Sep 15, 2005 at 19:06 UTC
    Have you thought about just using three different form fields and not relying on your user to put in commas and limit themselves to three entries?
Re: stripping email address regex
by ikegami (Patriarch) on Sep 15, 2005 at 19:03 UTC

    How about:

    my @emails = (split(/\s*,\s*/, $email))[0..2];

    Update: If you want to detect extras:

    my @emails = split(/\s*,\s*/, $email); if (@emails > 3) { ... warn ... } # Keep only the first three. splice(@emails, 3);

    Update: oh, if you don't want an array:

    $email = join(', ', (split(/\s*,\s*/, $email))[0..2]);

      The string "A pain to parse, RFC822 addresses are, hrmm?" <yoda@swamp.dagobah> would have its one address clobbered by that split . . .