代码之家  ›  专栏  ›  技术社区  ›  PapaDiHatti

正则表达式中的正则表达式迭代器与组不匹配

  •  1
  • PapaDiHatti  · 技术社区  · 6 年前

    如何从下面代码中的字符串s中提取test和again 。 目前我使用的是regex迭代器,它似乎不匹配正则表达式中的组,我在输出中再次得到测试和测试。

    #include <regex>
    #include <iostream>
    
    int main()
    {
        const std::string s = "<abc>{{Test}}</abc><def>{{Again}}</def>";
        std::regex rgx("\\{\\{(\\w+)\\}\\}");
        std::smatch match;
        std::sregex_iterator next(s.begin(), s.end(), rgx);
        std::sregex_iterator end;
        while (next != end) {
          std::smatch match = *next;
          std::cout << match.str() << "\n";
          next++;
        } 
        return 0;
    }
    

    试验 输出

    #include <regex>
    #include <iostream>
    
    int main()
    {
        const std::string s = "<abc>{{Test}}</abc><def>{{Again}}</def>";
        std::regex rgx("\\{\\{(\\w+)\\}\\}");
        std::smatch match;
    
        if (std::regex_search(s, match, rgx,std::regex_constants::match_any))
        {
            std::cout<<"Match size is "<<match.size()<<std::endl;
            for(auto elem:match)
            std::cout << "match: " << elem << '\n';
        }
    }
    

    另请注意,为什么需要两个反斜杠来避开或

    1 回复  |  直到 6 年前
        1
  •  1
  •   Wiktor Stribiżew    6 年前

    要访问您需要使用的捕获组的内容 .str(1) :

    std::cout << match.str(1) << std::endl;
    

    查看 C++ demo :

    #include <regex>
    #include <iostream>
    
    int main()
    {
        const std::string s = "<abc>{{Test}}</abc><def>{{Again}}</def>";
        // std::regex rgx("\\{\\{(\\w+)\\}\\}");
        // Better, use a raw string literal:
        std::regex rgx(R"(\{\{(\w+)\}\})");
        std::smatch match;
        std::sregex_iterator next(s.begin(), s.end(), rgx);
        std::sregex_iterator end;
        while (next != end) {
          std::smatch match = *next;
          std::cout << match.str(1) << std::endl;
          next++;
        } 
        return 0;
    }
    

    输出:

    Test
    Again
    

    注意,您不必使用双反斜杠在内部定义正则表达式转义序列 未经加工的 字符串文字(这里, R"(pattern_here)" )