Regular exp to validate email in C
Posted
by Liju Mathew
on Stack Overflow
See other posts from Stack Overflow
or by Liju Mathew
Published on 2010-06-01T07:53:43Z
Indexed on
2010/06/01
8:23 UTC
Read the original article
Hit count: 443
Hi,
We need to write a email validation program in C. We are planning to use GNU Cregex.h) regular expression.
The regular expression we prepared is
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
But the below code is failing while compiling the regex.
#include <stdio.h>
#include <regex.h>
int main(const char *argv, int argc)
{
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])?";
int status = 1;
char email[71];
regex_t preg;
int rc;
printf("The regex = %s\n", reg_exp);
rc = regcomp(&preg, reg_exp, REG_EXTENDED|REG_NOSUB);
if (rc != 0)
{
if (rc == REG_BADPAT || rc == REG_ECOLLATE)
fprintf(stderr, "Bad Regex/Collate\n");
if (rc == REG_ECTYPE)
fprintf(stderr, "Invalid Char\n");
if (rc == REG_EESCAPE)
fprintf(stderr, "Trailing \\\n");
if (rc == REG_ESUBREG || rc == REG_EBRACK)
fprintf(stderr, "Invalid number/[] error\n");
if (rc == REG_EPAREN || rc == REG_EBRACE)
fprintf(stderr, "Paren/Bracket error\n");
if (rc == REG_BADBR || rc == REG_ERANGE)
fprintf(stderr, "{} content invalid/Invalid endpoint\n");
if (rc == REG_ESPACE)
fprintf(stderr, "Memory error\n");
if (rc == REG_BADRPT)
fprintf(stderr, "Invalid regex\n");
fprintf(stderr, "%s: Failed to compile the regular expression:%d\n", __func__, rc);
return 1;
}
while (status)
{
fgets(email, sizeof(email), stdin);
status = email[0]-48;
rc = regexec(&preg, email, (size_t)0, NULL, 0);
if (rc == 0)
{
fprintf(stderr, "%s: The regular expression is a match\n", __func__);
}
else
{
fprintf(stderr, "%s: The regular expression is not a match: %d\n", __func__, rc);
}
}
regfree(&preg);
return 0;
}
The regex compilation is failing with the below error.
The regex = [a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
Invalid regex
main: Failed to compile the regular expression:13
What is the cause of this error? Whether the regex need to be modified?
Thanks, Mathew Liju
© Stack Overflow or respective owner