这是我的代码:
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
关于c++ - regex_search 和子串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40066805/