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

Regex 正则表达式迭代器与正则表达式中的组不匹配,regex,c++11,Regex,C++11,如何从下面代码中的字符串s中提取测试和重复测试。 目前我正在使用regex_迭代器,它似乎不匹配正则表达式中的组,我在输出中得到{{Test}}和{{reach}} #include <regex> #include <iostream> int main() { const std::string s = "<abc>{{Test}}</abc><def>{{Again}}</def>"; std::re

如何从下面代码中的字符串s中提取测试和重复测试。 目前我正在使用regex_迭代器,它似乎不匹配正则表达式中的组,我在输出中得到{{Test}}和{{reach}}

#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;
}
#包括
#包括
int main()
{
const std::string s=“{{Test}}{{reach}}”;
std::regex rgx(“\\{\\{(\\w+\\\}”);
std::smatch匹配;
std::sregx_迭代器next(s.begin()、s.end()、rgx);
std::sregx_迭代器端;
while(下一步!=结束){
std::smatch match=*下一步;

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


注意:您不必使用双反斜杠来定义原始字符串文本(此处为“
R”(此处为“pattern_)”
)中的正则表达式转义序列。

您所需要的就是(在第一个代码段中)。感谢这段代码。您是否知道为什么我们需要对{和}使用两个反斜杠@Kapil:如果使用原始字符串文字,则不需要将它们加倍。我更新了答案。我认为我使用的是原始字符串文字,没有两个反斜杠,这不是编译
#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';
    }
}
std::cout << match.str(1) << std::endl;
#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