使用扩展POSIX语法的C正则表达式与C++正则表达式中的不同行为
在使用 C POSIX 正则表达式库和 C++ 标准库实现时,我看到了不同的结果。这是我的代码:
string pattern = "s";
string testString = " ";
regex_t cre;
int status = regcomp(&cre, pattern.c_str(), REG_EXTENDED);
int result = (regexec(&cre, testString.c_str(), 0, 0, 0) == 0);
cout << "C: " << result << endl;
regex re(pattern, regex_constants::extended);
smatch sm;
cout << "C++: " << regex_search(testString, sm, re) << endl;
C 部分成功匹配空格,但 C++ 部分抛出此错误:
terminate called after throwing an instance of 'std::regex_error'
what(): Unexpected escape character.
我知道字符串文字被转义意味着模式匹配中使用的实际正则表达式应该是s. 我也只在使用 POSIX 扩展语法时看到这个问题。在C++版本中,如果我在构造正则表达式时不指定POSIX扩展语法,则默认为ECMAScript语法,并且能够正确解析。
这里发生了什么?