#include <stdio.h> #include <stdlib.h> #include <sys/types.h> void regex_match(const char *str,const char *regex); int main() { const char *regex="^[Mi]"; const char *string1="liutingwei is I"; const char *string2="I am liutingwei"; regex_match(string1,regex); regex_match(string2,regex); return 0; } void regex_match(const char *str,const char *regex) { regex_t *preg; if((preg=malloc(sizeof(regex_t)))==NULL) exit(0); if(regcomp(preg,regex,REG_EXTENDED|REG_NOSUB|REG_ICASE)!=0) exit(0); if(regexec(preg,str,0,NULL,0)==REG_NOMATCH) printf("\"%s\" doesn't match the regex %s\n",str,regex); else printf("\"%s\" match the regex %s\n",str,regex); if(preg) regfree(preg); }
|
这是自学正则表达式是写的一段代码,虽然比较简单,且可能考虑的不是很全面,但是很适合初学正则编程的,希望对那些初学的人有帮助。
上述代码在linux下用gcc编译运行通过。结果如下
"liutingwei is I" doesn't match the regex ^[Mi]
"I am liutingwei" match the regex ^[Mi]
阅读(867) | 评论(0) | 转发(0) |