Is this C++11 regex error me or the compiler?

前端 未结 3 1057
闹比i
闹比i 2020-11-27 17:34

OK, this isn\'t the original program I had this problem in, but I duplicated it in a much smaller one. Very simple problem.

main.cpp:

#include 

        
相关标签:
3条回答
  • 2020-11-27 17:46

    Regex support improved between gcc 4.8.2 and 4.9.2. For example, the regex =[A-Z]{3} was failing for me with:

    Regex error

    After upgrading to gcc 4.9.2, it works as expected.

    0 讨论(0)
  • 2020-11-27 18:11

    Update: <regex> is now implemented and released in GCC 4.9.0


    Old answer:

    ECMAScript syntax accepts [0-9], \s, \w, etc, see ECMA-262 (15.10). Here's an example with boost::regex that also uses the ECMAScript syntax by default:

    #include <boost/regex.hpp>
    
    int main(int argc, char* argv[]) {
      using namespace boost;
      regex e("[0-9]");
      return argc > 1 ? !regex_match(argv[1], e) : 2;
    }
    

    It works:

    $ g++ -std=c++0x *.cc -lboost_regex && ./a.out 1
    

    According to the C++11 standard (28.8.2) basic_regex() uses regex_constants::ECMAScript flag by default so it must understand this syntax.

    Is this C++11 regex error me or the compiler?

    gcc-4.6.1 doesn't support c++11 regular expressions (28.13).

    0 讨论(0)
  • 2020-11-27 18:12

    The error is because creating a regex by default uses ECMAScript syntax for the expression, which doesn't support brackets. You should declare the expression with the basic or extended flag:

    std::regex r4("[0-9]", std::regex_constants::basic);
    

    Edit Seems like libstdc++ (part of GCC, and the library that handles all C++ stuff) doesn't fully implement regular expressions yet. In their status document they say that Modified ECMAScript regular expression grammar is not implemented yet.

    0 讨论(0)
提交回复
热议问题