4

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?

StrikerFred
  • 105
  • 5
  • From what I've heard `std::regex` isn't properly/fully implemented. (But I don't know if that's the case here or something else.) – Qtax Apr 13 '13 at 11:33
  • I tried 20+ variations with escaping the `?`, parentheses, using `*` and `{x,y}` all failed in one way or another. I think `` is buggy. – JimR Apr 13 '13 at 11:39
  • Yes I've heard something similar, and that might actually be the case. I've already switched to boost regex (which work) but I'm waiting for more answers – StrikerFred Apr 13 '13 at 11:39

3 Answers3

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.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
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

Qtax
  • 33,241
  • 9
  • 83
  • 121
1

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.

brian beuning
  • 2,836
  • 18
  • 22
  • That's good to know. But I tested it in my code and it still doesn't work (same output as before) – StrikerFred Apr 13 '13 at 12:09
  • That's one way to do it, but just plain `std::regex re2(".*(a|xayy)");` also works. The default regular expression grammar is ECMAScript, which supports `?` right out of the box. – Pete Becker Apr 13 '13 at 14:57