谁能告诉我一个关于在 C/C++ 中使用正则表达式 (regex.h) 来搜索和/或提取正则表达式中的子模式的示例。
在 javascript 中,它会是这样的,
var str = "the string contains 123 dots and 344 chars";
var r = /the string contains ([0-9].*?) dots and ([0-9].*?) chars/;
var res = r.exec(str);
var dots = res[1];
var chars = res[2];
alert('dots ' + dots + ' and chars ' + chars);
我如何使用 c/c++ 中的 regex.h 来做到这一点(不是 boost 或任何其他库)?
thanks,
没有regex.h
在标准 C 或标准 C++ 中,所以我假设你的意思是POSIX 正则表达式库。 C 示例:
char const *str = "the string contains 123 dots and 344 chars";
char const *re_str = "the string contains ([0-9].*?) dots and ([0-9].*?) chars";
regex_t compiled;
regmatch_t *groups;
regcomp(&compiled, re_str, REG_EXTENDED);
ngroups = compiled.re_nsub + 1;
groups = malloc(ngroups * sizeof(regmatch_t));
regexec(&compiled, str, ngroups, groups, 0);
for (size_t i = 0; i < ngroups; i++) {
if (groups[i].rm_so == (size_t)(-1))
break;
else {
size_t len = groups[i].rm_eo - groups[i].rm_so;
char buf[len + 1];
memcpy(buf, str + groups[i].rm_so, len);
buf[len] = '\0';
puts(buf);
}
}
free(groups);
(添加您自己的错误检查。有关更多详细信息,请参阅这个答案.)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)