微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

与 regex_search 一起使用的 match_results::size 的返回值

如何解决与 regex_search 一起使用的 match_results::size 的返回值

我不确定我是否完全理解 std::match_results::size 返回的内容。 根据 cppreference 它“返回子匹配的数量”。

我可能误解了这个描述。 在我看来,函数返回的是第一次出现的结果,而不是完整的字符串。 matches[0] 是完全匹配,matches[1] 是子匹配,matches[2] 是字符串的其余部分。

#include <iostream>
#include <string>
#include <regex>

int main ()
{
    std::string s ("this subject has a submarine as a subsequence called subaru");
    std::smatch matches;
    std::regex pattern ("\\b(sub)([^ ]*)");   // matches words beginning by "sub"
    
    std::cout << "Target sequence: " << s << std::endl;
    std::cout << "Regular expression: /\\b(sub)([^ ]*)/" << std::endl;
    std::cout << "The following matches and submatches were found:" << std::endl;
    
    std::regex_search (s,matches,pattern);
    std::cout << "size: " << matches.size() << "\n";


    std::cout << "Results: \n";
    while (std::regex_search (s,pattern)) {
        std::cout << matches[0] << " " << matches[1] << " " << matches[2] << "\n";  // match,submatch,rest
        s = matches.suffix().str();
    }

  return 0;
}

基于: https://en.cppreference.com/w/cpp/regex/regex_search

http://www.cplusplus.com/reference/regex/regex_search/?kw=regex_search

演示http://coliru.stacked-crooked.com/a/056462e884896604

描述表明,如果提到 string 调用 size() 应该返回数字 4。(因为句子中有四个“子”) 实际上,size() 返回匹配项和子匹配项,但只返回第一次出现。 此功能是否记录错误或我误解了它的工作原理?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。