C ++子模式匹配

谁能告诉我一个关于在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或任何其他库)?

谢谢,

标准C或标准C ++中没有regex.h ,所以我假设您的意思是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); 

(添加您自己的错误检查。有关详细信息,请参阅此答案 。)

C ++中唯一可用的正则表达式是boost::regex ,这就是下一个标准所采用的。 语法是:

 boost::regex expr( "the string contains (\\d*) dots and (\\d*) chars" ); boost::smatch match; if ( regex_match( text, match, expr ) ) { // We have a match, std::string dots = match[1]; std::string chars = match[2]; // ... } 

C和C ++都没有“regex.h”。 最新版本的C ++(通常称为C ++ 0x)将具有正则表达式支持,但它或多或少会是Boost.Regex。 所以你也可以问一下,“我如何使用Boost.Regex?”