C ++子模式匹配 [英] C++ Subpattern Matching

查看:147
本文介绍了C ++子模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以请告诉我有关在正则表达式使用C / C ++的正则表达式(regex.h)来搜索和/或提取子模式的例子。

can anyone please show me an example about using regex (regex.h) in C/C++ to search and/or extracting subpattern in a regex.

在JavaScript中,这将是这样的事情,

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

我如何能够在C / C ++做到这一点使用regex.h(不提升或任何其他库)??

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

感谢,

推荐答案

有没有 regex.h 中的标准C或C ++标准,所以我假设你的意思 POSIX正前pression库。 C的例子:

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

(添加您自己的错误检查。有关详细信息,请参见这个答案

这篇关于C ++子模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆