[英]Difference between std::regex_match & std::regex_search?
下面的程序已编写为使用 C++11 std::regex_match和std::regex_search获取“日”信息。 但是,使用第一个方法返回false
,第二个方法返回true
(预期)。 我阅读了文档并且已经存在与此相关的 SO 问题,但是我不明白这两种方法之间的区别以及何时应该使用它们中的任何一种? 对于任何常见问题,它们都可以互换使用吗?
regex_match 和 regex_search 的区别?
#include<iostream>
#include<string>
#include<regex>
int main()
{
std::string input{ "Mon Nov 25 20:54:36 2013" };
//Day:: Exactly Two Number surrounded by spaces in both side
std::regex r{R"(\s\d{2}\s)"};
//std::regex r{"\\s\\d{2}\\s"};
std::smatch match;
if (std::regex_match(input,match,r)) {
std::cout << "Found" << "\n";
} else {
std::cout << "Did Not Found" << "\n";
}
if (std::regex_search(input, match,r)) {
std::cout << "Found" << "\n";
if (match.ready()){
std::string out = match[0];
std::cout << out << "\n";
}
}
else {
std::cout << "Did Not Found" << "\n";
}
}
Did Not Found
Found
25
在这种情况下,为什么第一个正则表达式方法返回false
? regex
似乎是正确的,因此理想情况下两者都应该返回true
。 我通过改变运行上述程序std::regex_match(input,match,r)
来std::regex_match(input,r)
发现它仍然会返回false.
有人能解释一下上面的例子,以及这些方法的一般用例吗?
regex_match
仅在匹配整个输入序列时返回true
,而regex_search
将成功,即使只有一个子序列与regex
匹配。
引自 N3337,
§28.11.2/2
regex_match
[re.alg.match]
效果:确定正则表达式e
与所有字符序列[first,last)
之间是否存在匹配。...
如果存在这样的匹配,则返回true
,否则返回false
。
上面的描述是针对regex_match
重载的,它需要一对迭代器到要匹配的序列。 其余的重载是根据此重载定义的。
相应的regex_search
重载描述为
§28.11.3/2
regex_search
[re.alg.search]
效果:确定[first,last)
中是否存在与正则表达式e
匹配的子序列。...
如果存在这样的序列,则返回true
,否则返回false
。
在您的示例中,如果您将regex
修改为r{R"(.*?\\s\\d{2}\\s.*)"};
regex_match
和regex_search
都会成功(但匹配结果不仅仅是日期,而是整个日期字符串)。
这很简单。 regex_search
查看字符串以查找字符串的任何部分是否与正则表达式匹配。 regex_match
检查整个字符串是否与正则表达式匹配。 作为一个简单的例子,给定以下字符串:
"one two three four"
如果我在那个字符串上使用regex_search
和表达式"three"
,它会成功,因为"three"
可以在"one two three four"
但是,如果我改用regex_match
,它将失败,因为"three"
不是整个字符串,而只是其中的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.