#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<regex.h>
#define SUBSLEN 10 /* 匹配子串的数量 */
#define EBUFLEN 128 /* 错误消息buffer长度 */
using namespace std;
int isEMail(int i,char *mailID);
int main(void)
{
char mailID[50]="";
cout <<"请输入邮件号码:";
cin >> mailID;
cout << "你输入的邮件号码为:"<<mailID<<endl;
if(isEMail(1,mailID))
{
cout << "输入的邮件号码格式正确" <<endl;
}
else
{
cout << "输入的邮件号码格式错误,请重新输入" <<endl;
}
cout <<"请输入收寄日期:";
cin >> mailID;
cout << "你输入的收寄日期为:"<<mailID<<endl;
if(isEMail(2,mailID))
{
cout << "输入的收寄日期格式正确" <<endl;
}
else
{
cout << "输入的收寄日期格式错误,请重新输入" <<endl;
}
cout <<"请输入金额数字:";
cin >> mailID;
cout << "你输入的金额数字为:"<<mailID<<endl;
if(isEMail(3,mailID))
{
cout << "输入的金额数字正确" <<endl;
}
else
{
cout << "输入的金额数字错误,请重新输入" <<endl;
}
}
int isEMail (int i,char *src)
{
size_t len;
regex_t re; /* 存储编译好的正则表达式,正则表达式在使用之前要经过编译 */
regmatch_t subs [SUBSLEN]; /* 存储匹配到的字符串位置 */
char matched [EBUFLEN]; /* 存储匹配到的字符串 */
char errbuf [EBUFLEN]; /* 存储错误消息 */
int err,j;
char pattern[256] = "";
switch (i)
{
case 1:
strcpy(pattern,"^([\\!#\\$%&'\\*\\+/\\=?\\^`\{\\|\\}~a-zA-"
"Z0-9_-]+[\\.]?)+[\\!#\\$%&'\\*\\+/\\=?\\^`\{\\|\\}"
"~a-zA-Z0-9_-]+@{1}((([0-9A-Za-z_-]+)([\\.]{1}[0-9A"
"-Za-z_-]+)*\\.{1}([A-Za-z]){1,6})|(([0-9]{1,3}[\\."
"]{1}){3}([0-9]{1,3}){1}))$");
break;
case 2:
strcpy(pattern,"(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]"
"{1}[1-9][0-9]{2}|[1-9][0-9]{3})(((0[13578]|1[02])("
"0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12]["
"0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{"
"2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468]["
"048]|[3579][26])00))0229)");
break;
case 3:
strcpy(pattern,"^\\d{5,12}$");
break;
default:
break;
}
cout << src <<endl;
cout << pattern << endl;
err = regcomp(&re, pattern, REG_EXTENDED);
if (err)
{
len = regerror(err, &re, errbuf, sizeof(errbuf));
return 0;
}
err = regexec(&re, src, (size_t) SUBSLEN, subs, 0);
if (err == REG_NOMATCH)
{
/* 没有匹配成功 */
regfree(&re);
return 0;
}
else if (err)
{
/* 其它错误 */
len = regerror(err, &re, errbuf, sizeof(errbuf));
regfree(&re);
return 0;
}
/* 如果不是REG_NOMATCH并且没有其它错误,则模式匹配上 */
/*
printf("\nOK, has matched ...\n\n");
for (j = 0; j <= re.re_nsub; j++)
{
len = subs[j].rm_eo - subs[j].rm_so;
if (j == 0)
{
printf ("begin: %d, len = %d ", subs[j].rm_so, len);
}
else
{
printf("subexpression %d begin: %d, len = %d ", j, subs[i].rm_so, len);
}
memcpy (matched, src + subs[j].rm_so, len);
matched[len] = '\0';
printf("match: %s\n", matched);
}
*/
regfree(&re); /* 用完了别忘了释放 */
return (1);
}
参考:http://dev.mjxy.cn/a-Email-regular-expression.aspx
http://deerchao.net/tutorials/regex/regex.htm