首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >std::regex_match和std::regex_search的区别是什么?

std::regex_match和std::regex_search的区别是什么?
EN

Stack Overflow用户
提问于 2014-11-02 13:06:59
回答 1查看 20.6K关注 0票数 35

以下程序已编写为使用C++11 std::regex_match & std::regex_search获取“日期”信息。但是,使用第一个方法返回false,使用第二个方法返回true(预期)。我阅读了文档和已经存在的与此相关的问题,但我不明白这两种方法之间的区别,以及我们何时应该使用其中一种方法?对于任何常见的问题,它们都可以互换使用吗?

Difference between regex_match and regex_search?

代码语言:javascript
运行
复制
#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";
    }
}

输出

代码语言:javascript
运行
复制
Did Not Found

Found

 25 

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

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

EN

回答 1

Stack Overflow用户

发布于 2014-11-02 13:20:21

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

代码语言:javascript
运行
复制
"one two three four"

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

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

票数 19
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26696250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档