regex_search

         在regex_match()里边只能看到regex和输入的字符串是不是全部匹配上了,匹配上了就返回true,否则false。然而他不能返回匹配到的子字符串;regex_search()和regex_match()参数类型是一样的;返回的也是bool类型;但是它还可以查找到匹配的子字符串;将捕捉到的结果会保存在std::smatch里边;比如:

Std::smatch match;  用过调用match[1] 和 match[2]来查看捕获到的第一个和第二个捕获组;

#include <iostream>
#include <regex>
int main() {
    std::regex r("//(.+)(\d{4})");
    std::string str;
    while(true)
    {
        if(!std::getline(std::cin,str) || str == "q")
        {
            break;
        } else
        {
            std::smatch match;
            if(std::regex_search(str,match,r))
            {
                std::cout << "find this str : " << match[1] << "***" << match[2]<< std::endl;
            }else
            {
                std::cout << "invaild argument"  << std::endl;
            }
            std::cout << "prefix() :" << match.prefix() << std::endl;
            std::cout << "suffix() :" << match.suffix() << std::endl;
        }
    }
    return 0;
}

输入:

kslkf//kfskl89438sd

结果:

find this str : kfskl8***9438
prefix() :kslkf
suffix() :sd

其中std::smatch.prefix()返回的是匹配到的捕获组之前的部分

  std::smatch.suffix()返回的是匹配到捕获组之后的部分;

原文地址:https://www.cnblogs.com/boost/p/10425663.html