【发布时间】:2016-05-02 04:30:32
【问题描述】:
我在 C 中使用 POSIX 正则表达式 regex.h 来计算一个短语在英语文本片段中出现的次数。
但是regexec(...) 的返回值仅说明是否找到匹配项。所以我尝试使用nmatch 和matchptr 来查找不同的外观,但是当我从matchptr 打印出匹配项时,我刚刚收到第一个短语的第一个索引出现在我的文本中。
这是我的代码:
#include <sys/types.h>
#include <regex.h>
#include <stdio.h>
#define MAX_MATCHES 20 //The maximum number of matches allowed in a single string
void match(regex_t *pexp, char *sz) {
regmatch_t matches[MAX_MATCHES];
if (regexec(pexp, sz, MAX_MATCHES, matches, 0) == 0) {
for(int i = 0; i < MAX_MATCHES; i++)
printf("\"%s\" matches characters %d - %d\n", sz, matches[i].rm_so, matches[i].rm_eo);
}
else {
printf("\"%s\" does not match\n", sz);
}
}
int main(int argc, char* argv[]) {
int rv;
regex_t exp;
rv = regcomp(&exp, "(the)", REG_EXTENDED | REG_ICASE);
if (rv != 0) {
printf("regcomp failed\n");
}
match(&exp, "the cat is in the bathroom.");
regfree(&exp);
return 0;
}
如何使此代码同时报告字符串 the cat is in the bathroom 中正则表达式 (the) 的两个不同匹配项?
【问题讨论】: