2

Why is the POSIX basic regular expression "[" considered valid in POSIX C but has a syntax error in C++.

Here's a program to illustrate the issue:

#include <cassert>
#include <iostream>
#include <regex>
#include <regex.h>

int main(int argc, char** argv)
{
    const char pattern[] = "\\["; // Two backslashes needed to get one

    std::cout << "pattern: \"" << pattern << "\"" << std::endl;

    regex_t reg;
    int     status = ::regcomp(&reg, pattern, 0);
    std::cout << "::regcomp() " << (status ? "failed" : "succeeded") <<
            std::endl;

    try {
        std::regex regex(pattern, std::regex::basic);
        std::cout << "std::regex() succeeded" << std::endl;
    }
    catch (const std::regex_error& ex) {
        std::cout << "std::regex() failed" << std::endl;
    }
}

On my system (CentOS 7, g++ 4.8.5):

$ g++ -std=c++11 -Wall a.c
$ ./a.out
pattern: "^\[$"
::regcomp() succeeded
std::regex() failed
$ 
Steve Emmerson
  • 7,702
  • 5
  • 33
  • 59
  • Your code works fine for me with `GCC v9.1.1`. (after adding `int` as `main` return type!) – Galik May 17 '19 at 14:55
  • Also you are not comparing `C` with `C++` here you are comparing `Linux` implementation of `POSIX` regex with `GCC C++11` implementation of `POSIX` regex – Galik May 17 '19 at 15:01

0 Answers0