Regexp matching fails with invalid special open parenthesis

Viewed 2499

I am trying to use regexps in c++11, but my code always throws an std::regex_error of Invalid special open parenthesis.. A minimal example code which tries to find the first duplicate character in a string:

std::string regexp_string("(?P<a>[a-z])(?P=a)"); // Nothing to be escaped here, right?
std::regex  regexp_to_match(regexp_string);
std::string target("abbab");
std::smatch matched_regexp;
std::regex_match(target, matched_regexp, regexp_to_match);
for(const auto& m: matched_regexp)
{
    std::cout << m << std::endl;
}

Why do I get an error and how do I fix this example?

3 Answers

There are 2 issues here:

Use

std::string regexp_string(R"(([a-z])\1)");
std::regex regexp_to_match(regexp_string);
std::string target("abbab");
std::smatch matched_regexp;
if (std::regex_search(target, matched_regexp, regexp_to_match)) {
    std::cout << matched_regexp.str() << std::endl;
}
// => bb

See the C++ demo

The R"(([a-z])\1)" raw string literal defines the ([a-z])\1 regex that matches any lowercase ASCII letter and then matches the same letter again.

The reason your regex crashes for you is because named groups not supported by std::regex. However you can still use what is available to find the first duplicate char in string:

#include <iostream>
#include <regex>

int main()
{
    std::string s = "abc def cde";
    std::smatch m;
    std::regex r("(\\w).*?(?=\\1)");

    if (std::regex_search(s, m, r))
        std::cout << m[1] << std::endl;

    return 0;
}

Prints

c
Related