std = c ++ 11和std = gnu ++ 11之间的C ++标准正则表达式差异

问题描述 投票:1回答:1

使用正则表达式和gnu扩展名编译代码时,正则表达式的行为似乎有所不同。

以下代码在与-std = c ++ 11进行编译时会产生异常,但是-std = gnu ++ 11可以工作:

#include <regex>
#include <iostream>

int main(int argc, char **argv) {

    std::string rex { "\\[1\\]" };
    std::string str { "[1]" };
    std::regex regex(rex, std::regex::extended);
    auto match = std::regex_match(str.begin(), str.end(), regex);
    std::cout << "Result is " << match << std::endl;
    return 0;
}

我尝试了从4.9.4到9.2的gcc,并且具有相同的行为。为什么此代码的行为有所不同的任何想法?

c++ regex c++11 gcc gnu
1个回答
0
投票

std::regex::extended使用extended POSIX regular expressions。根据那些语法规则,反斜杠只能位于“特殊字符”之前,该特殊字符是.[\()*+?{|^$之一。左括号[是特殊字符,而右括号]不是特殊字符。因此,您的正则表达式应为"\\[1]"而不是"\\[1\\]"

查看标准库源代码,regex_scanner.tcc中包含以下内容:

#ifdef __STRICT_ANSI__
      // POSIX says it is undefined to escape ordinary characters
      __throw_regex_error(regex_constants::error_escape,
                  "Unexpected escape character.");
#else
      _M_token = _S_token_ord_char;
      _M_value.assign(1, __c);
#endif

这表明它是GNU扩展,允许转义非特殊字符。我不知道此扩展在哪里记录。

© www.soinside.com 2019 - 2024. All rights reserved.