Below program has been written to fetch the "Day" information using the C++11 std::regex_match & std::regex_search. However, using the first method returns false
and second method returns true
(expected). I read the documentation and already existing SO question related to this, but I do not understand the difference between these two methods and when we should use either of them? Can they both be used interchangeably for any common problem?
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"(sd{2}s)"};
//std::regex r{"\s\d{2}\s"};
std::smatch match;
if (std::regex_match(input,match,r)) {
std::cout << "Found" << "
";
} else {
std::cout << "Did Not Found" << "
";
}
if (std::regex_search(input, match,r)) {
std::cout << "Found" << "
";
if (match.ready()){
std::string out = match[0];
std::cout << out << "
";
}
}
else {
std::cout << "Did Not Found" << "
";
}
}
Output
Did Not Found
Found
25
Why first regex method returns false
in this case?. The regex
seems to be correct so ideally both should have been returned true
. I ran the above program by changing the std::regex_match(input,match,r)
to std::regex_match(input,r)
and found that it still returns false.
Could somebody explain the above example and, in general, use cases of these methods?
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…