Sinto
Sinto

Reputation: 3997

Regex email special character validation

I need a regex email validation with special characters.

Rules:

Current Regex:

^[a-zA-Z0-9]+([\w\.\'\!\#\$\%\&\*\+\-\/\=\?\^\`\{\|\}\~])+([a-zA-Z0-9])+@(([a-zA-Z0-9\.\-])+.)+([a-zA-Z0-9]{2,8})+$

Test patterns:

[email protected] > TRUE
e#[email protected] > TRUE
e#[email protected] > TRUE
[email protected] > FALSE
[email protected] > FALSE
#[email protected] > FALSE
e#@eee.eee > FALSE

I need a Regex that will validate as:

[email protected] > TRUE
e#[email protected] > TRUE
e#[email protected] > TRUE
[email protected] > TRUE
[email protected] > TRUE
#[email protected] > FALSE
e#@eee.eee > FALSE

Upvotes: 0

Views: 3669

Answers (2)

Jan
Jan

Reputation: 43169

While you have your answer, please note that you don't have to escape everything in square brackets, meaning:

^
[a-zA-Z0-9]+
([-.'!#$%&*+-\/=?^`{|}~]*)
([a-zA-Z0-9])+
@
([a-zA-Z0-9]+\.)+
[a-zA-Z0-9]{2,8}
$

does the same and is by far more readable. Additionally, the * is supposed to be in the parentheses.


As a side note, I'd rather use a simpler expression like \S+@\S+ and actually try to send an email to that address - email addresses tend to be more complicated than previously thought.

Upvotes: 1

Shen Yudong
Shen Yudong

Reputation: 1230

^[a-zA-Z0-9]+([\w\.\'\!\#\$\%\&\*\+\-\/\=\?\^\`\{\|\}\~])*([a-zA-Z0-9])+@([a-zA-Z0-9]+\.)+[a-zA-Z0-9]{2,8}$

just replace + with * or ? after ([\w\.\'\!\#\$\%\&\*\+\-\/\=\?\^\{\|}\~])`, it will match you expect. update as you need.

Upvotes: 1

Related Questions