Question

I don't manage to use back references in regular expression in c++. After trying more esoteric things, I tried this simple script on gcc 4.8.1:

#include <iostream>
#include <regex>
#include <string>

using namespace std;

int main() {
    regex e("(..)\\1");
    string s("aaaa");
    if (regex_match(s,e))
        cout << "match" << endl;
    return 0;
}

but it produces a runtime error. I tried various flags in regex_constants like ECMAScript or grep but to no avail. What's wrong with this way of using back references in C++ regex engine?

Just to make sure I was not missing something trivial, I tried this in Java

class TestIt
{
    public static void main (String[] args) throws java.lang.Exception
    {
        final String s = "aaaa";
        final String e = "(..)\\1";
        if (s.matches(e))
            System.out.printf("match");
    }
};

and obviously it prints match as expected, which is reassuring.

Was it helpful?

Solution

The regex engine included in gcc (in libstdc++) is not fully working yet. This regex works as expected on clang. So this issue has nothing to do with the way C++ treats regular expressions; rather it depends on the compiler used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top