How to check the email address with regular expression?

Hello everyone,
I want to check the email address with regex.And I attached my code,but whatever the parameter(char **email) is email or not , it always return “No Match”.
Can you help me to change it right? At the same time, I also want to get a better method from you.
Thank you~
code:

int is_email_valid
{
int status, i;
int cflags = REG_EXTENDED;
regmatch_t pmatch[1];
const size_t nmatch = 1;
regex_t reg;
const charpattern = “^w**@w*([-.]w*)*.w*([-.]w+)$";
char**buf = email;
regcomp(&reg, pattern, cflags);
status = regexec(&reg, buf, nmatch, pmatch, 0);
if (status REG_NOMATCH) {
printf(“No Match\n”);
}
else if (status 0) {
printf(”Match:“);
for (i = pmatch[0].rm_so; i < pmatch[0].rm_eo; ++i) {
putchar(buf);
}
printf(”");
}
regfree(&reg);
return 0;
}

1 Like

Really a general C++ or Regex question. Lots of good posts found in Google about why you should not do this — and examples of workable solutions if you must. Not a CC2D-x issue IMO tho.

Cory Trese wrote:

Really a general C++ or Regex question. Lots of good posts found in Google about why you should not do this — and examples of workable solutions if you must. Not a CC2D-x issue IMO tho.
Yeah, it’s write by C,and I found it in google. I want to use it in my cocos2dx protection., but couldn’t get the right result.
Always thank you.

I solved this problem after read a book which named “Regular Expression”.I write a new regex like this “^[a-zA-Z0-9][a-zA-Z0-9_.]+@[a-zA-Z0-9_]+.[a-zA-Z0-9_.]+$”.
Thanks everyone~

std::string email = “testing@gmail.com”;
bool valid = std::regex_match(email, std::regex(“^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$”) );

if( valid ) {
……
}

1 Like