c++ std regex question mark issue

2019-07-07 10:48发布

问题:

I'm having troubles with std regex. I can't make the question mark quantifier work. The call to regex_match will always return 0.

I also tried with {0,1} which doesn't behave like I expected either: it behaves like a + quantifier.

Here is my code :

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

int main(int argc, char **argv){

    regex e1("ab?c");
    cout << regex_match("ac", e1) << endl;    // expected : 1, output 0
    cout << regex_match("abc", e1) << endl;   // expected : 1, output 0
    cout << regex_match("abbc", e1) << endl;  // expected : 0, output 0

    regex e2("ab{0,1}c");
    cout << regex_match("ac", e2) << endl;    // expected : 1, output 0
    cout << regex_match("abc", e2) << endl;   // expected : 1, output 1
    cout << regex_match("abbc", e2) << endl;  // expected : 0, output 1

    return 0;
}

I used the following command to compile:

g++ -std=c++11 main.cpp -o regex_test

Am i doing something wrong here? Or why isn't it working?

回答1:

str::regex is mostly not implemented in gcc (at the time of writing). See section 28 at: http://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.2011



回答2:

Your regular expression code is fine. The implementation that you're using is not. It provides a header that declares a bunch of things that the library implements badly. If a commercial package did that it would be roundly criticized, and rightly so. You get what you pay for.



回答3:

The POSIX standard for regular expressions defines two type, basic and extended. The ? operator is an extended feature. Apparently you use

std::regex re2(".*(a|xayy)", std::regex::extended)

to get the extended features.



标签: c++ regex std