以下程序已编写为使用C++11 std::regex_match & std::regex_search获取“日期”信息。但是,使用第一个方法返回false
,使用第二个方法返回true
(预期)。我阅读了文档和已经存在的与此相关的问题,但我不明白这两种方法之间的区别,以及我们何时应该使用其中一种方法?对于任何常见的问题,它们都可以互换使用吗?
Difference between regex_match and 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.
有人能解释一下上面的例子,以及这些方法的一般用例吗?
发布于 2014-11-02 13:20:21
这很简单。regex_search
查看字符串,以确定字符串的任何部分是否与正则表达式匹配。regex_match
检查整个字符串是否与正则表达式匹配。作为一个简单的示例,给定以下字符串:
"one two three four"
如果我对带有表达式"three"
字符串使用regex_search
,它将会成功,因为可以在"one two three four"
中找到"three"
但是,如果我使用regex_match
,它将失败,因为"three"
不是整个字符串,而只是其中的一部分。
https://stackoverflow.com/questions/26696250
复制相似问题