mardi 11 février 2020

How to regex square brackets "[]" in C++?

Here's the regex:

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

and these are my test cases:

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

And this works fine here: https://regexr.com

But, when I try to validate my cases using C++11 regex.h. I get invalid matches. I've figured out that it's because of square brackets that I need to escape.

Here's the C++ code,

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

How may I escape the square brackets, so my code can work fine.

Thanks :)

Aucun commentaire:

Enregistrer un commentaire