为什么POSIX基本正则表达式“ [”在POSIX C中被认为是有效的,但在C ++中却存在语法错误。
这是一个说明问题的程序:
#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(®, 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;
}
}
在我的系统上(CentOS 7,g ++ 4.8.5):
$ g++ -std=c++11 -Wall a.c
$ ./a.out
pattern: "^\[$"
::regcomp() succeeded
std::regex() failed
$