E G*_*E G 6 c c++ regex posix c++11
在使用 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;
Run Code Online (Sandbox Code Playgroud)
C 部分成功匹配空格,但 C++ 部分抛出此错误:
terminate called after throwing an instance of 'std::regex_error'
what(): Unexpected escape character.
Run Code Online (Sandbox Code Playgroud)
我知道字符串文字被转义意味着模式匹配中使用的实际正则表达式应该是\s. 我也只在使用 POSIX 扩展语法时看到这个问题。在C++版本中,如果我在构造正则表达式时不指定POSIX扩展语法,则默认为ECMAScript语法,并且能够正确解析。
这里发生了什么?
regex_constants::extended触发不支持速记字符类的POSIX ERE 正则表达式语法。请注意,C模块支持作为非标准扩展。regex.h\s
要匹配regex_constants::extended启用的 POSIX ERE 风格中的任何空格,您需要使用string pattern = "[[:space:]]".
但是,您应该只依赖默认的 ECMAScript 风格,并使用
regex re(pattern);
// or
regex re(pattern, std::regex::ECMAScript);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
132 次 |
| 最近记录: |