C++11 标准::regex_match 返回额外的字符

C++11 std::regex_match returning extra character

本文关键字:返回 字符 match 标准 regex C++11      更新时间:2023-10-16

可能的重复项:
gcc4.7 有关于正则表达式的错误吗?

我按照 http://www.cplusplus.com/reference/std/regex/regex_match/上的示例并在 Ubuntu 12.04 64 位上编译,使用 g++ 版本 4.6.3

以下是我的输出:

string literal matched
string object matched
range matched
string literal with 3 matches
string object with 3 matches
range with 3 matches
the matches were: [subject] [sub] [bject] 

虽然示例输出为:

string literal matched
string object matched
range matched
string literal with 3 matches
string object with 3 matches
range with 3 matches
the matches were: [subject] [sub] [ject]

请注意,在我的机器上,[bject]被提取了不正确。有什么想法吗?

根据 gcc 实现状态(版本 4.6.3),正则表达式库尚未完全实现。它不会引发任何错误,也不会提供警告。这确实令人不快。

但是,其他人以前也观察到了这一点,更新的版本也是如此:

  • 这是 C++11 正则表达式错误是我还是编译器?
  • regex_match和regex_search的区别?
  • gcc 4.8 或更早版本在正则表达式方面有问题吗?
  • 正则表达式误解或只是破坏了实现?

常见的建议是进一步使用 Boost.Regex 或尝试使用其他编译器。

请参阅此答案以获取进一步阅读。

您可以将

示例简化为:

std::string s("subject");
std::regex e("(sub)(.*)");
std::smatch sm;
std::regex_match(s, sm, e);

更有趣的是:

std::string s("subject");
std::regex e("(sub)(ject)");
std::smatch sm;
std::regex_match(s, sm, e);

所以,这看起来像是GNU实现中的一个错误。