【问题标题】:C++ get matches from regex_iteratorC++ 从 regex_iterator 获取匹配
【发布时间】:2013-05-23 18:14:07
【问题描述】:

我试图通过逐行读取文件来从文件中获取一些匹配项。我的代码是这样的:

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 对象,但我不知道如何声明一个(它总是给我错误的参数列表。我怎样才能让迭代器给我一个匹配对象?

【问题讨论】:

  • 最后我听说,g++ 正则表达式还没有工作。

标签: c++ regex class object iterator


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多