以下是 C++11 标准中的一些引用:
28.11.3 regex_search [re.alg.search]
m
是 regex_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
。有人可以提供一个示例(正则表达式模式和要匹配的文本)以显示何时可能吗?
换句话说,对于 text
和 re
的值,下面的程序不会断言:
#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
,返回true
,match_results::size
,返回0
和 match_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/