dimanche 13 septembre 2020

Repeating Regex Match Sequence

My strings are formatted like this [label] blah blah blah [label] blah blah blah [label] blah blah blah [label] blah blah blah ... repeating any number of times.

The regex I thought would work (and that seems to work in other regex engines) is ^(\[([^\]]*)\]([^\[]*))+ however this only matches the first [label] blah blah blah section with matches:

  1. the whole string
  2. [label] blah blah blah
  3. label
  4. blah blah blah

If I use ^([^\[]*)(\[([^\]]*)\]([^\[]*))(\[([^\]]*)\]([^\[]*)).* I can match 2 sequences but how would I get this to work for x number of sequences? Can I change the regex engine c++ uses?

full code for completeness:

int main() {
//    const regex match_string(R"((\[([^\]]*)\]([^\[]*))(\[([^\]]*)\]([^\[]*)).*)");
    const regex match_string(R"((\[([^\]]*)\]([^\[]*))+)");
    string line = "[label] blah blah blah [label] blah blah blah [label] blah blah blah [label] blah blah blah";
    smatch matches;
    bool res = regex_match(line, matches, match_string);
    if (res) {
        for (const auto &match : matches) {
            cout << match << endl;
        }
    } else {
        cout << "no match" << endl;
    }

}

Aucun commentaire:

Enregistrer un commentaire