Itsme
Itsme

Reputation: 11

Error in regular expression for e-mail addresses

I have a regular expression to validate an e-mail address. It looks like

^[a-z0-9]+([-+._][a-z0-9]+)*@[a-z0-9]+([-.][a-z0-9]{2,})*\.[a-z0-9]+([-.][a-z0-9]{2,})*$

In most cases it works properly but when I type the e-mail like "[email protected]" this regular expression does not match, although it is a correct e-mail address. Addresses like [email protected] do match.
How can I fix this expression to avoid this error?

Upvotes: 1

Views: 90

Answers (3)

Peter R
Peter R

Reputation: 414

Unless you have a good reason don't use self rolled regex to validate email addresses. They are a complex beast and someone else has already done the work for you!

Here's how to use the module

# Gives us say and always a good idea
use Modern::Perl;

use Email::Valid;

my @addrs = qw/ [email protected]
                [email protected]
                qwerty\@mail.com  /;
foreach (@addrs) {
    print "$_ is ";
    print 'in' unless Email::Valid->address($_);
    say   'valid'
}

Which outputs

[email protected] is valid
[email protected] is valid
qwerty\@mail.com is invalid

I actually discovered this module in answering this question and it's better than the one I was using before. So thanks very much for asking :)

Upvotes: 0

asontu
asontu

Reputation: 4659

This part (at the beginning):

[a-z0-9]+([-+._][a-z0-9]+)*

Is causing the problem. It's saying you want 1 or more letters or number, followed by 0 or more iterations of a combination of a symbol and 1 or more letters. You probably wanna say "a letter or number at the start and then any of the following characters 0 or more times" like so:

[a-z0-9][a-z0-9+._-]*

The part after the @ is allowing dashes for dots, are you sure this is what you want? In the interest of doing more than just giving you the code that "works", take a look at Debuggex to see how your current regex works so you can improve it :) Gives this nice visual view:

Regular expression visualization

Upvotes: 1

Mehdi Khademloo
Mehdi Khademloo

Reputation: 2812

use this regex to validating the emails

^[A-Za-z]([A-Za-z1-9][\.\-\_]?[A-Za-z1-9]?)+@[A-Za-z]+\.[A-Za-z]{3,}$

Upvotes: 0

Related Questions