std::regex_match 和 std::regex_search 之间的区别?

Difference between std::regex_match & std::regex_search?

本文关键字:std regex 区别 match search 之间      更新时间:2023-10-16

下面的程序已被编写为使用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"(sd{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 

为什么在这种情况下,第一个正则表达式方法返回falseregex似乎是正确的,因此理想情况下两者都应该返回true。我通过将std::regex_match(input,match,r)更改为std::regex_match(input,r)来运行上述程序,发现它仍然返回false.

有人可以解释上面的例子,以及这些方法的一般用例吗?

regex_match 仅在匹配整个输入序列时返回true,而即使只有一个子序列与regex匹配,regex_search也会成功。

引用N3337,

§28.11.2/2 regex_match [重新匹配]

影响:确定正则表达式 e所有字符序列[first,last)之间是否存在匹配。 ... 如果存在此类匹配项,则返回true,否则false返回。

上面的描述是针对regex_match重载,它将一对迭代器带到要匹配的序列。其余重载是根据此重载定义的。

相应的regex_search过载描述为

§28.11.3/2 regex_search [重新搜索]

影响:确定[first,last)中是否存在与正则表达式e匹配的某个子序列... 如果存在此类序列,则返回true,否则false返回。


在您的示例中,如果您修改regexr{R"(.*?sd{2}s.*)"}; regex_matchregex_search将成功(但匹配结果不仅仅是日期,而是整个日期字符串(。

示例的修改版本的现场演示,其中regex_matchregex_search捕获并显示当天。

这很简单。 regex_search查看字符串以查找字符串的任何部分是否与正则表达式匹配。 regex_match检查整个字符串是否与正则表达式匹配。 作为一个简单的示例,给定以下字符串:

"one two three four"

如果我在该字符串上使用表达式 regex_search "three" ,它将成功,因为"three"可以在"one two three four"中找到

但是,如果我改用regex_match,它将失败,因为"three"不是整个字符串,而只是其中的一部分。