c++ - std::regex 中的错误?

标签 c++ regex c++11

代码如下:

#include <string>
#include <regex>
#include <iostream>

int main()
{
    std::string pattern("[^c]ei");
    pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";
    std::regex r(pattern); 
    std::smatch results;   
    std::string test_str = "cei";

    if (std::regex_search(test_str, results, r)) 
        std::cout << results.str() << std::endl;      

    return 0;
}

输出:

cei

使用的编译器是gcc 4.9.1

我是学习正则表达式的新手。我预计不会输出任何内容,因为 "cei" 与此处的模式不匹配。我做对了吗?有什么问题?

更新:

此问题已被报告并确认为错误,有关详细信息,请访问此处: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63497

最佳答案

这是实现中的一个错误。我试过的其他几个工具不仅同意你的模式与你的输入不匹配,而且我试过这个:

#include <string>
#include <regex>
#include <iostream>

int main()
{
  std::string pattern("([a-z]*)([a-z])(e)(i)([a-z]*)");
  std::regex r(pattern);
  std::smatch results;
  std::string test_str = "cei";

  if (std::regex_search(test_str, results, r))
  {
    std::cout << results.str() << std::endl;

    for (size_t i = 0; i < results.size(); ++i) {
      std::ssub_match sub_match = results[i];
      std::string sub_match_str = sub_match.str();
      std::cout << i << ": " << sub_match_str << '\n';
    }
  }
}

这基本上与您所拥有的相似,但为了简单起见,我将 [:alpha:] 替换为 [a-z],并且我还临时替换了 [ ^c][a-z] 因为这似乎使它正常工作。这是它打印的内容(Linux x86-64 上的 GCC 4.9.0):

cei
0: cei
1:
2: c
3: e
4: i
5:

如果我将 [a-z] 替换为 [^c] 并只是将 f 放在那里,它正确地说模式没有'匹配。但是如果我像你一样使用[^c]:

std::string pattern("([a-z]*)([^c])(e)(i)([a-z]*)");

然后我得到这个输出:

cei
0: cei
1: cei
terminate called after throwing an instance of 'std::length_error'
  what():  basic_string::_S_create
Aborted (core dumped)

所以它声称匹配成功,结果[0]是预期的“cei”。然后,results[1] 也是“cei”,我想这可能没问题。但是随后 results[2] 崩溃了,因为它试图构造一个长度为 18446744073709551614 且 begin=nullptr 的 std::string。这个巨大的数字正好是 2^64 - 2,又名 std::string::npos - 1(在我的系统上)。

所以我认为某处存在一个差一错误,其影响可能不仅仅是虚假的正则表达式匹配——它可能会在运行时崩溃。

关于c++ - std::regex 中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26272592/

相关文章:

php - 正则表达式忽略第二个前瞻

javascript - 如何忽略/允许 Javascript 中的多个换行符替换正则表达式

c++ - std::set 自定义比较器用于 2D 点

c++ - Boost Ublas 矩阵所有元素的平方根

c++ - 将可变参数模板参数解包到初始化列表中

c++ - 什么会导致初始化顺序损坏堆栈?

c++ - 派生类中的基构造函数调用

javascript - 动态比较正则表达式模式的匹配精度

c++ - 打印给定字符串中不重复的第一个字符

c++ - 字符数组集(固定大小)和相等重载