提问者:小点点

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


下面的程序使用C++11 std::regex_match&; std::regex_search。 但是,使用第一个方法返回false,第二个方法返回true(预期)。 我阅读了文档,并且已经存在与此相关的问题,但是我不明白这两种方法之间的区别,以及我们什么时候应该使用它们中的任何一种? 它们是否可以在任何共同的问题上互换使用?

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 

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

有人能解释一下上面的例子和这些方法的一般用例吗?


共2个答案

匿名用户

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

引用N3337,

§28.11.2/2regex_match[re.alg.match]

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

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

相应的regex_search重载描述为

§28.11.3/2regex_search[re.alg.search]

效果:确定[first,last)中是否存在与正则表达式e匹配的子序列。...返回true如果存在这样的序列,则返回false否则返回false

在您的示例中,如果将regex修改为r{r“(.*?\s\d{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”不是整个字符串,而只是其中的一部分。