c++从regex_iterator获取匹配项

C++ get matches from regex_iterator

本文关键字:获取 iterator regex c++      更新时间:2023-10-16

我正试图通过逐行读取文件来获得一些匹配。我的代码是:

std::regex e("id="(.+?)"|title="(.+?)"|summary="(.+?)"|first="(.+?)"|last="(.+?)"");
std::regex_iterator<std::string::iterator> rit ( line.begin(), line.end(), e );
std::regex_iterator<std::string::iterator> rend;
while (rit!=rend) {
    std::cout << rit->str() << std::endl;
    ++rit;
}

我已经尝试使用regex_search和smatch对象,但它停止在行的第一个匹配。我发现regex_iterator完成了这项工作,但它给了我整个匹配(例如id="123456",而不是123456),这是有意义的,但我只需要数字。

根据http://www.cplusplus.com/reference/regex/regex_iterator/operator*/的解引用,迭代器会给我一个match_results对象,但我不知道如何声明一个(它总是给我一个糟糕的参数列表)。如何让迭代器给我一个smatch对象?

match_results对象上调用str()将返回整个当前匹配。要查看各个子匹配项,在调用中传递一个索引:

for (int i = 0; i < rit->size(); ++i)
    std::cout << rit->str(i) << 'n';

您可能必须遍历匹配,每次调用regex_match以每次获得更新的match_results对象。