Boost regexp - 搜索结果的空终止

发布于 2024-08-18 21:19:01 字数 266 浏览 4 评论 0原文

  boost::regex re;
  re = "(\\d+)";
  boost::cmatch matches;
  if (boost::regex_search("hello 123 world", matches, re))
    {
    printf("Found %s\n", matches[1]); 
    }

结果:“找到 123 个世界”。我只想要“123”。这是空终止的问题,还是只是误解了 regex_search 的工作原理?

  boost::regex re;
  re = "(\\d+)";
  boost::cmatch matches;
  if (boost::regex_search("hello 123 world", matches, re))
    {
    printf("Found %s\n", matches[1]); 
    }

Result: "Found 123 world". I just wanted the "123". Is this some problem with null-termination, or just misunderstanding how regex_search works?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

指尖上得阳光 2024-08-25 21:19:01

您不能像这样将 matches[1]sub_match 类型的对象)传递给 printf 。事实上,您不能指望它会给出任何有用的结果,因为 printf 需要一个 char 指针。相反,使用:

cout << "Found " << matches[1] << endl;

或者如果您想使用 printf:

printf("Found %s\n", matches[1].str().c_str());

您可以使用 matches[1].str() 获取带有结果的 std::string 对象。

You can't pass matches[1] (an object of type sub_match<T>) to printf like that. The fact that it gives any useful result at all is something you can't count on, since printf expects a char pointer. Instead use:

cout << "Found " << matches[1] << endl;

Or if you want to use printf:

printf("Found %s\n", matches[1].str().c_str());

You can get an std::string object with the result using matches[1].str().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文