c++ - 当 regex_search 返回 true 时,零是否始终匹配 "matches"?

标签 c++ regex c++11

以下是 C++11 标准中的一些引用:

28.11.3 regex_search [re.alg.search]

mregex_search 的参数,类型为 match_results

2 Effects: Determines whether the re is some sub-sequence within [first,last) that matches the regular expression e. The parameter flags is used to control how the expression is matched against the character sequence. Returns true if such a sequence exists, false otherwise.

3 Postconditions: m.ready() == true in all cases. If the function returns false, then the effect on parameter m is unspecified except that m.size() returns 0 and m.empty() returns true. Otherwise the effects on parameter m are given in Table 143.

表 143 说明了以下关于 m[0].matched 的内容:

true if a match was found, and false otherwise.

以上似乎暗示regex_search有可能返回true,同时m[0].matched到为 false。有人可以提供一个示例(正则表达式模式和要匹配的文本)以显示何时可能吗?

换句话说,对于 textre 的值,下面的程序不会断言:

#include <regex>
#include <cassert>
int main()
{
    char re[] = ""; // what kind of regular expression must it be?
    char text[] = ""; // what kind of input text must it be?
    std::cmatch m;
    assert(std::regex_search(text, m, std::regex(re)) == true);
    assert(m[0].matched == false);
}

最佳答案

您误解了后置条件信息,因为 C++11 标准 (N3337) 在该部分包含冗余措辞。

如果 regex_search 返回 false,意味着在输入字符串中的任何地方都没有找到匹配项,那么 match_results 对象的状态是未指定的,除了成员函数match_results::ready,返回truematch_results::size,返回0match_results::empty,返回 true

在那种情况下,match_results::operator[] 的结果是未指定的,您不应该调用它。

另一方面,如果 regex_search 返回 true,这意味着找到了匹配项,在这种情况下 m[0].matched 将始终为 true。在这种情况下,它不可能为 false

最新的 N3936 草案对此进行了澄清,该草案在表 143 中简单说明:

m[0].matched | true

带来这个措辞变化的问题报告可以是viewed here .引用它:

There's an analogous probem in Table 143: the condition for m[0].matched is "true if a match was found, false otherwise." But Table 143 gives post-conditions for a successful match, so the condition should be simply "true".

关于c++ - 当 regex_search 返回 true 时,零是否始终匹配 "matches"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25085615/

相关文章:

c++ - 论文中的概率密度函数,使用 C++ 实现,未按预期工作

c++ - Visual Studio 2012 :error LNK1117: syntax error in option 'MAPINFO:LINES'

c++ - 在 C++ 中的进程之间共享 CGAL 的几何结构

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

C++ exp LUT(查找表)

c++ - 仅在 void* typedef 中被忽略的限定词

c++ - 我可以 std::forward 折叠表达式中的参数吗?

c - 使用 regexec 进行分组

正则表达式匹配所有 unicode 引号

javascript - 将 "id"传递给 Controller ​​并传递给 JavaScript