std::regex_match的结果似乎是错误的

Result of std::regex_match seems wrong

本文关键字:结果 错误 似乎是 match regex std      更新时间:2023-10-16

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

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

#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) 编译

我必须以不同的方式构建程序,因为它在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,如预期的那样。

根据@LogicStuff发布的链接,这是因为传入临时对象意味着匹配项指向当临时对象超出范围时无效的迭代器。因此,您看到的可能是删除临时字符串时留下的垃圾。