c++ std regex question mark issue

淺唱寂寞╮ 提交于 2019-12-10 17:44:23

问题


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.



来源:https://stackoverflow.com/questions/15987278/c-std-regex-question-mark-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!