Jassi
Jassi

Reputation: 541

Regular expression in Perl for email splitting

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?

Upvotes: 3

Views: 4631

Answers (5)

Bill Ruppert
Bill Ruppert

Reputation: 9026

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";
}

Upvotes: 1

lalit
lalit

Reputation: 21

$str='j@[email protected]@..coding.com';
$user=qw();
$domain=qw();
while($str=~m/\@/g){
    $user=$`;
    $domain=$';
}
print "user -> $user\n";
print "domain->$domain\n";

Upvotes: 2

Eugene Yarmash
Eugene Yarmash

Reputation: 149973

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.

Upvotes: 8

Konerak
Konerak

Reputation: 39773

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.

Upvotes: 6

Nathan Fellman
Nathan Fellman

Reputation: 127538

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 =~ /(.*)@([^@]*)$/);

Upvotes: 2

Related Questions