我对使用C没有经验,我需要使用PCRE来获得匹配。
这里是我的源代码示例:如何使用PCRE获取所有匹配组?
int test2()
{
const char *error;
int erroffset;
pcre *re;
int rc;
int i;
int ovector[OVECCOUNT];
char *regex = "From:([^@]+)@([^\r]+)";
char str[] = "From:[email protected]\r\n"\
"From:[email protected]\r\n"\
"From:[email protected]\r\n";
re = pcre_compile (
regex, /* the pattern */
0, /* default options */
&error, /* for error message */
&erroffset, /* for error offset */
0); /* use default character tables */
if (!re) {
printf("pcre_compile failed (offset: %d), %s\n", erroffset, error);
return -1;
}
rc = pcre_exec (
re, /* the compiled pattern */
0, /* no extra data - pattern was not studied */
str, /* the string to match */
strlen(str), /* the length of the string */
0, /* start at offset 0 in the subject */
0, /* default options */
ovector, /* output vector for substring information */
OVECCOUNT); /* number of elements in the output vector */
if (rc < 0) {
switch (rc) {
case PCRE_ERROR_NOMATCH:
printf("String didn't match");
break;
default:
printf("Error while matching: %d\n", rc);
break;
}
free(re);
return -1;
}
for (i = 0; i < rc; i++) {
printf("%2d: %.*s\n", i, ovector[2*i+1] - ovector[2*i], str + ovector[2*i]);
}
}
在本演示中,输出仅是:
0: From:[email protected]
1: regular.expressions
2: example.com
我要输出所有的火柴;我怎样才能做到这一点?
不要使用正则表达式,而要使用真正的解析器。邮件协议允许的不仅仅是简单的邮箱地址。 – Gumbo 2009-09-14 14:11:46
这是pcre的演示,我只想知道如何在匹配组中使用pcre。 感谢您的评论。 – tbmvp 2009-09-15 01:57:14
你应该参考这篇文章:http://stackoverflow.com/questions/7785557/pcre-match-all-groups-in-c – soulmachine 2011-11-29 08:51:24