C++ 如何使用regex方括号“;[……”是;在C++;?

C++ 如何使用regex方括号“;[……”是;在C++;?,c++,regex,c++11,escaping,C++,Regex,C++11,Escaping,这是正则表达式: ((([a-z])*Map|map)\\[((MapFields::([a-z]|[A-Z])*)|(([a-z]|[A-Z])*))|("([a-z]|[A-Z]|[0-9]|_)*")*\\]( )*=( )*([a-z]|[A-Z])*;) 以下是我的测试用例: 映射[MapFields::abCd]=abCd myMap[MapFields::abCd]=abCd 映射[abCd]=abCd 映射[AbCd]=AbCd 映射[AbCd]=AbCd myMap[AbC

这是正则表达式:

((([a-z])*Map|map)\\[((MapFields::([a-z]|[A-Z])*)|(([a-z]|[A-Z])*))|("([a-z]|[A-Z]|[0-9]|_)*")*\\]( )*=( )*([a-z]|[A-Z])*;)
以下是我的测试用例:

  • 映射[MapFields::abCd]=abCd
  • myMap[MapFields::abCd]=abCd
  • 映射[abCd]=abCd
  • 映射[AbCd]=AbCd
  • 映射[AbCd]=AbCd
  • myMap[AbCd]=AbCd
  • 地图[“AB123”]=abCd
  • 地图[“AB_CD”]=abCd
  • 地图[“AB_CD”]=abCd
这在这里很管用:

但是,当我尝试使用C++11 regex.h验证我的案例时。我得到了无效的匹配。我发现,正是因为方括号,我才需要逃避

这是C++代码,

    string data[10] = {
        //array of cases
    };

    try {
    regex rgx(regex string);

    for ( int i = 0 ; i < 10 ; i++ ) {
        if ( regex_match(data[i], rgx) ) {
            cout << "string literal matched\n";
        }
        else {
            cout << "string literal unmatched\n";
        }
    }
    }
    catch ( exception ex ) {
        cout << "Exception: " << ex.what() << endl;
    }

字符串数据[10]={
//一系列案例
};
试一试{
正则表达式rgx(正则表达式字符串);
对于(int i=0;i<10;i++){
if(regex_匹配(数据[i],rgx)){

cout简化后,您可以执行以下操作:

int main()
{
    std::string data[] = {
        "map[MapFields::abCd] = abCd;",
        "myMap[MapFields::abCd] = abCd;",
        "map[abCd] = AbCd;",
        "map[AbCd] = abCd;",
        "map[AbCd] = abCd;",
        "myMap[AbCd] = abCd;",
        "map[\"AB123\"]=abCd;",
        "map[\"AB_CD\"]=abCd;",
        "map[\"AB_CD\"]=abCd;"
    };

    try {
        std::regex rgx(R"(((?:[a-z])*Map|map)\[(MapFields::[a-zA-Z]*|[a-zA-Z]*|"[a-zA-Z0-9_]*")\]\s*=\s*([a-zA-Z]*);)");

        for (const auto& s : data) {
            std::smatch res;
            if (std::regex_match(s, res, rgx) ) {
                std::cout << s << " [matched]\n";
                for (auto e : res) {
                    std::cout << e << std::endl; // Display matched groups
                }
            } else {
                std::cout << s << " [unmatched]\n";
            }
        }
    }
    catch (const std::exception& ex) {
        std::cout << "Exception: " << ex.what() << std::endl;
    }
}
intmain()
{
std::字符串数据[]={
“映射[MapFields::abCd]=abCd;”,
“myMap[MapFields::abCd]=abCd;”,
“映射[abCd]=abCd;”,
“映射[AbCd]=AbCd;”,
“映射[AbCd]=AbCd;”,
“myMap[AbCd]=AbCd;”,
“映射[\“AB123\”]=abCd;”,
“映射[\“AB\u CD\”]=abCd;”,
“映射[\“AB\u CD\”]=abCd;”
};
试一试{
std::regex rgx(R)((((?:[a-z])*Map | Map)\[(映射字段::[a-zA-z]*.[a-zA-z]*.“[a-zA-Z0-9|]+\s*=\s*([a-zA-z]*);
用于(常数自动和s:数据){
std::smatch res;
if(std::regex_匹配(s、res、rgx)){

std::cout除非您使用raw,否则您也需要转义,因为
\[
不是有效的。@某个程序员我也尝试过。程序停止抛出std::regex\u错误,但仍然出现不匹配。我将“[”匹配部分替换为“(.{1})”,但仍然没有运气:(([C++11 regex.h”你是说C++ 11还是POSIX?看起来你的代码使用了前者……在标准C++上使用“.h”是非标准的,在所有的平台/编译器上都是不工作的(也就是说,在任何情况下,支持POSIX正则表达式的任何东西)。<代码> [AZ] [[ZZ] [09]><代码>可以简单地是<代码> [AZ-Z099] ] /Cord>。