posix正则表达式,多个匹配结果,为何只取到了第一个???
如题,明明有多个匹配的结果,为何运行结果是只匹配了第一个呢?还望高人指点!
用的是Fedora12系统中自带的regex.h文件。
源码及运行结果:
- C/C++ code
#include <stdio.h>#include <string.h>#include <sys/types.h>#include <regex.h>// 提取子串char* getsubstr(char *s, regmatch_t *pmatch){ static char buf[100] = {0}; memset(buf, 0, sizeof(buf)); memcpy(buf, s+pmatch->rm_so, pmatch->rm_eo - pmatch->rm_so); return buf;}int main(int argc, char **argv){ int status, i; int cflags = REG_EXTENDED; regmatch_t pmatch[5]; const size_t nmatch = 5; regex_t reg; const char *pattern = "[[:lower:]]+"; // 正则表达式 char buf[] = "COMEdavID2012@gmail.com"; // 待搜索的字符串 regcomp(®, pattern, cflags); status = regexec(®, buf, nmatch, pmatch, 0); if(status == REG_NOMATCH) printf("No Match\n"); else { printf("Match:\n"); for(i = 0; i < nmatch; i++) { if(pmatch[i].rm_so == -1) continue; char *p = getsubstr(buf, &pmatch[i]); printf("[%d, %d): %s\n", pmatch[i].rm_so, pmatch[i].rm_eo, p); } } regfree(®); return 0;}
运行结果:
[zcm@t #139]$make
gcc -c -o a.o a.c
gcc -o a a.o
[zcm@t #140]$./a
Match:
[4, 7): dav
[zcm@t #141]$
[解决办法]
不清楚啊。
perl里是 /[a-z]+/g
[解决办法]
regexec() is used to match a null-terminated string against the precompiled pattern buffer, preg. nmatch and pmatch are used to provide information regarding the location of any matches. eflags may be the bitwise-or of one or both of REG_NOTBOL and REG_NOTEOL which cause changes in matching behavior described below.