Regex to validate email is failing if 2 "@" are provided
We have followed the regex for validating RFC 2822 standard.
The function is as follows:
int isValidEmail(const char *email_id)
{
/* Regular expression to validate email */
const char *reg_exp =
"[a-z0-9!#$%&'*+-/=?^_`{|}~]+(\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@([a-z0-9]([a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9]([a-z0-9-]*[a-z0-9])?$";
regex_t preg;
/* Compile the regular expression */
if (regcomp(&preg, reg_exp, REG_EXTENDED|REG_NOSUB|REG_ICASE) != 0)
return FAILURE;
/* Execute the regex, 0 for success */
if (regexec(&preg, email_id, (size_t)0, NULL, 0) != 0)
return FAILURE;
regfree(&preg);
return SUCCESS;
}
But if I provide emails like "test@test@test.com", the emails are getting accepted.
Is there any problem with this regex?
开发者_运维技巧Appreciate the help in advance.
Thanks, Mathew Liju
Add a ^
at the beginning of the regex. It matches the beginning of line. Without ^
regex will match the substring test@test.com
as it is a valid email id matching the regex.
Your first character class contains the sequence +-/
, which is treated as a range. In addition to those three characters, the range will match a period or a comma, which I'm pretty sure you don't want. You should move the hyphen to the end of the class, like it is in all the other classes.
That's the only structural problem I see with the regex. As for whether it's the right regex for an email address, well, there's no such thing. There are huge variations depending on the context and what you're doing with the regex. When it comes to email-address regexes, you're always flying seat-of-the-pants. :P
Try adding a start anchor ^
as:
"^[a-z0-9!#$%&'*+-/=?^_`{|}~]+(\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@([a-z0-9]([a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9]([a-z0-9-]*[a-z0-9])?$";
精彩评论