0

I would like to grab everything before ] in aasd{123;'asd'aaaa]asd. So I tried to create regex but regex.h works weird.

Closest I get: ".*[^\\]]" which gives me: aasd{123;'asd'aaaa]

#include <regex.h>
#include <iostream>
#include <cstring>

using namespace std;

int main(){


    const char* phrase = "aasd{123;'asd'aaaa]asd";
    const char* expression = "........"; // <- what should be here? 

    size_t group_size = 5;
    regmatch_t *pmatch = new regmatch_t[group_size];
    memset(pmatch, 0, sizeof(regmatch_t) * group_size);

    regex_t regex;

    int reti = regcomp(&regex, expression, REG_EXTENDED);

    if (reti){
        cout << "Error1" << reti <<endl;
        return false;
    }

    reti = regexec(&regex, phrase, group_size, pmatch, 0);
    if (reti){
        cout << "Error2 " << reti <<endl;
        return false;
    }

    int len = 0, i = 0;
    char result[10000];

    for (i = 0; pmatch[i].rm_so != -1; i++){
        len = pmatch[i].rm_eo - pmatch[i].rm_so;
        memcpy(&result, phrase + pmatch[i].rm_so, len);
        cout << "num " << i << " " << result << endl;
   }
}

1 Answer 1

1

^[^\\]]* is what you are looking for.

In english: from the start of the line (^) match everything which is not a "]" ([^\\]]*).


UPDATE

There must be an odd quirk to this library, ^[^]]* passed the test.

The "^[^\\]]*" literal get complied into ^[^\]]*. This should have been an escaped ] in a character class [], but this library turned it into a character class containing not \ followed by any number of ]s.

^ [^\] ]* instead of ^ [^\]]*.

Fortunately, there is an alternate form which allows for []] to match ] if it's the only character in the character class. This extended to [^]] to match a non ].

In short… try ^[^]]*.

Sign up to request clarification or add additional context in comments.

2 Comments

Just paste your regexp in my code as const char* expression = "^[^\\]]*";
@zie1ony heh, odd quirk of this library. I updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.