开发者

C++ Subpattern Matching

can anyone please show me an example about using 开发者_运维问答regex (regex.h) in C/C++ to search and/or extracting subpattern in a regex.

in javascript, it will be something like this,

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);

how can i do this using regex.h in c/c++ (not boost or any other libraries) ??

thanks,


There is no regex.h in standard C or standard C++, so I'm assuming you mean the POSIX regular expression library. C example:

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);

(Add your own error checking. For more details, see this answer.)


The only regular expressions readily available in C++ is boost::regex, and that is what has been adopted for the next standard. And the syntax is:

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];
    //  ...
}


Neither C nor C++ has a "regex.h". The newest version of C++ (commonly called C++0x) will have regular expression support, but it will be Boost.Regex, more or less. So you may as well just ask, "How do I use Boost.Regex?"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜