以下程序使用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)
更改为 std::regex_match(input,r)
运行了上面的程序,并发现它仍然返回 false。
能有人解释一下上面的例子,以及这些方法的通常用途吗?
(\d{2})
周围添加了括号以创建一个捕获组。根据match_results
文档,match[0]
总是返回整个匹配表达式,而match[1]
返回第一个子匹配等等。在这种情况下,我们只有一个捕获组,即天数,因此它存储在第一个子匹配中。 - Praetorian