首页 > 解决方案 > 如何在 C++ 中正则表达式方括号“[]”?

问题描述

这是正则表达式:

((([a-z])*Map|map)\\[((MapFields::([a-z]|[A-Z])*)|(([a-z]|[A-Z])*))|("([a-z]|[A-Z]|[0-9]|_)*")*\\]( )*=( )*([a-z]|[A-Z])*;)

这些是我的测试用例:

这在这里工作正常:https ://regexr.com

但是,当我尝试使用 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;
    }

我该如何转义方括号,以便我的代码可以正常工作。

谢谢 :)

标签: c++regexc++11escaping

解决方案


简化后,您可以这样做:

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;
    }
}

演示


推荐阅读