Regex_search和子字符串匹配

regex_search and substring matching

本文关键字:字符 字符串 串匹配 search Regex      更新时间:2023-10-16

下面是我的代码:

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

现场演示