c++ - regex_search 和子串匹配

标签 c++ regex

这是我的代码:

std::string var = "(1,2)";
std::smatch match;
std::regex rgx("[0-9]+");
if(std::regex_search(var,match,rgx))
    for (size_t i = 0; i < match.size(); ++i)
        std::cout << i << ": " << match[i] << '\n';

我希望能够同时提取 1 和 2,但到目前为止输出只是第一个匹配项 (1)。我似乎无法弄清楚为什么,我的大脑被炸了。这可能是显而易见的事情

最佳答案

regex_match 的元素用于匹配正则表达式中的组。

在一个稍微修改过的例子中

std::string var = "(11b,2x)";
std::smatch match;
std::regex rgx("([0-9]+)([a-z])");
if(std::regex_search(var,match,rgx))
    for (size_t i = 0; i < match.size(); ++i)
        std::cout << i << ": " << match[i] << '\n';

你会得到以下输出:

0: 11b
1: 11
2: b

你想要的是使用std::regex_iterator查看所有匹配项:

auto b = std::sregex_iterator(var.cbegin(), var.cend(), rgx);
auto e = std::sregex_iterator();

std::for_each(b, e, [](std::smatch const& m){
    cout << "match: " << m.str() << endl;
});

这将产生所需的输出:

match: 1
match: 2

live demo

关于c++ - regex_search 和子串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40066805/

相关文章:

c++ - 引用类型的初始化无效?

c++ - 在 Boost.Spirit 中,为什么 vector 需要融合包装器(包装在结构中),而不是变体?

c++ - 如何在它之外的模板类中使用模板参数?

regex - Bash 脚本进程名称正则表达式

regex - 使用 sed,在不同长度的单词周围加上引号

java - Pattern.matches 不起作用,而 replaceAll 起作用

c++ - 如何从一维数组中提取子图像?

python - 正则表达式可以在 regex101.com 上运行,但不能在 python 中运行

javascript - 使用正则表达式搜索元素的节点列表