Regular expression in Perl for email splitting

4.5k views Asked by At

I was asked by my peer that how you will look for last @if more than one@` is present.

Example:

j@[email protected]@..coding.com

So it should display j@[email protected] as username and ..coding.com as domain name. Is there any one liner regex in Perl to get the desired output?

5

There are 5 answers

1
Bill Ruppert On BEST ANSWER

Use Email::Address. These things are too hard for simple re's to do correctly. Oops, didn't read op close enough, but this code works for splitting emails.

use strict;
use warnings;
use Email::Address;

my $line = '[email protected];[email protected]';
my @addresses = Email::Address->parse($line);
for my $address (@addresses) {
  print $address->format, "\n";
}
2
lalit On
$str='j@[email protected]@..coding.com';
$user=qw();
$domain=qw();
while($str=~m/\@/g){
    $user=$`;
    $domain=$';
}
print "user -> $user\n";
print "domain->$domain\n";
1
Nathan Fellman On

quantifiers in Perl are greedy by default. that means that they'll grab as much as possible.

what you want is a simple:

($username, $domain) = ($string =~ /(.*)@(.*)$/);

If you want to be 100% certain that the second part has no @, you can use:

($username, $domain) = ($string =~ /(.*)@([^@]*)$/);
2
Konerak On

Just use the greedyness:

/(.*)@(.*)$/

The first part will take as much as it can until it encounters an @. The last part will take everything behind the @ until the end of the line.

0
Eugene Yarmash On
my ($username, $domain) = $str =~ /(.*)@(.*)/;

More information in perlre:

By default, a quantified subpattern is "greedy", that is, it will match as many times as possible (given a particular starting location) while still allowing the rest of the pattern to match.