下面的程序已编写为使用 C++11 std::regex_match和std::regex_search获取“Day”信息。但是,使用第一种方法返回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)
to运行了上面的程序std::regex_match(input,r)
,发现它仍然返回false.
有人可以解释上面的例子,以及这些方法的一般用例吗?