• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
p-boost-q
博客园    首页    新随笔    联系   管理    订阅  订阅
regex_iterator

绝对不能在循环中通过regex_search获取模式在源字符串所有的实例;应该改为regex_iterator或则regex_token_iterator,一般情况下需要位一个特定的容器来指定一个尾迭代器,但是在std::regex_iterator 里边直接调用构造函数就会生成一个尾迭代器;例如:
std::regex_iterator end;

而不需要:std::regex_iterator end(std::end(str));

但是为了遍历全部的源字符串,我们需要这样来制定一个首迭代器;

Std::regex_iterator iter(std::begin(str),std::end(str), r );

其中的r是正则表达式;

接下来提取输入的单词

#include <iostream>
#include <regex>
int main() {

    std::regex r("[\\w]+");
    std::string str;
    while(true)
    {
        if(!std::getline(std::cin,str) || str == "q")
        {
            break;
        }else
        {
            //typedef regex_iterator<string::const_iterator>  sregex_iterator;
            const std::sregex_iterator end;
            for(std::sregex_iterator iter(std::begin(str),std::end(str),r);iter != end;++iter)
            {
                std::cout <<  "\"" << *iter->begin()  << "\"" << std::endl;
            }
        }
    }
    return 0;
}

输入:

djsf jkdfn , klj 

输出:

"djsf"
"jkdfn"
"klj"

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