• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
p-boost-q
博客园    首页    新随笔    联系   管理    订阅  订阅
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()返回的是匹配到捕获组之后的部分;

 

posted on 2019-02-24 11:28  p-boost-q  阅读(1424)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3