std :: regex_match的结果似乎错了

时间:2016-07-05 13:33:27

标签: c++ regex

我正在尝试理解以下代码的行为。

我认为这可能是一个错误,因为我的结果看起来不对。

#include <iostream>
#include <regex>

int main(int ac, char **av)
{
  std::regex reg("lib(.*)\\.so");
  std::smatch match;
  std::cout << std::regex_match(std::string("libscio.so"), match, reg) << std::endl;
  std::cout << match.str(1) << std::endl;

  return 0;
}

我期待

1
scio

但它给了我

1
ocio

在x86_64 GNU / Linux上用gcc版本4.9.2(Debian 4.9.2-10)编译

1 个答案:

答案 0 :(得分:2)

我不得不以不同的方式构建程序,因为在VS 2015中它不会编译。也许这会导致你的问题,你的编译器也是如此?注意字符串临时变量。

#include <iostream>
#include <regex>

int main(int ac, char **av)
{
  std::regex reg("lib(.*)\\.so");
  std::smatch match;
  std::string target = "libscio.so";
  std::cout << std::regex_match(target, match, reg) << std::endl;
  std::cout << match.str(1) << std::endl;

  return 0;
}

按照预期,这将在VS 2015中产生1和scio。

根据发布的the link @LogicStuff,这是因为传入临时对象意味着匹配指向临时超出范围时失效的迭代器。所以你看到的可能是临时字符串被删除时留下的垃圾。

相关问题