您的位置:首页 > 编程语言 > C语言/C++

c语言中的正则

2016-02-20 00:25 330 查看
#include <stdio.h>
#include <string.h>
#include <regex.h>

#define SUBSLEN 10
#define BUFLEN 1024 //储存找到的字符串所需空间

int main()
{
char* string="asd@asd.com,qwe@qwe.cn,zxc@zxc.org";
char* pattern="[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z0-9]{1,3}";

regex_t regex; //编译后的正则储存在这里
regmatch_t subs[SUBSLEN]; //子表达式储存在这里
regcomp(®ex, pattern, REG_EXTENDED);

int offset=0;
while(regexec(®ex,string+offset,SUBSLEN,subs,0)==0)
{
static char matched[BUFLEN]; //匹配的字符串
int len=subs[0].rm_eo-subs[0].rm_so;

memcpy(matched,string+offset+subs[0].rm_so,len);
matched[len]='\0';
printf("match: %s\n", matched);

offset+=subs[0].rm_eo+1;
}

regfree(®ex);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: