2

In the last two hours I've tried to understand why the line of code from below

std::regex matchPattern{R"(?<=\@)(.*?)(?=\=)"};

throws Microsoft C++ exception: std::regex_error at memory location ....

I've tested the regular expresion with online tools and notepad++ and everything works just fine. When I'm trying to use it in my c++ app I get the runtime error from above on initialization. I am using c++14

Thanks in advance for your help.

RaduSR
  • 67
  • 5
  • 1
    I tried this and didn't get any error. It might be possible to replicate the error if a [mcve] is posted. – wally Jul 12 '18 at 14:57
  • 1
    Does it work with `std::regex matchPattern("^[^@[]*");`? Note you do not need to escape `[` inside a character class. – Wiktor Stribiżew Jul 12 '18 at 14:58
  • Sorry guys. By mistake I've added the wrong regex ... (i guess I am a little bit tired :) ). I've updated the regex in the initial question – RaduSR Jul 12 '18 at 15:03
  • C++ std::regex does not support lookbehind. Probably you want `R"(@([^=]+))"` and grab the Group 1 value. Please share your code. See [**this C++ demo**](https://ideone.com/Btbu0H). – Wiktor Stribiżew Jul 12 '18 at 16:01
  • checkout this https://stackoverflow.com/questions/8359566/regex-to-match-symbols – Haseeb Mir Jul 07 '20 at 00:20

1 Answers1

1

C++14 std::regex (any of its flavors) does not support lookbehind construct.

You may use R"(@([^=]+))" and grab the Group 1 value. Note that R"( and )" are the raw string literal boundaries, and the @([^=]+) is the real string pattern that matches @ and then matches and captures 1+ chars other than = into Group 1.

See this C++ demo:

#include <regex>
#include <string>
#include <iostream>
using namespace std;

int main() {
    std::regex matchPattern(R"(@([^=]+))");
    std::string s("@test=boundary");
    std::smatch matches;
    if (std::regex_search(s, matches, matchPattern)) {
        std::cout<<matches.str(1);
    }
    return 0;
}

Output:

test
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563