zoukankan      html  css  js  c++  java
  • boost中regex的使用

    boost是对STL的补充,regex是其中一个模块。各方法类别很多,本文记录常用方法。

    引入头文件<boost/regex.hpp>

    1. regex_match

      regex reg("\\d{3}");
      string str = "123";
      bool b = regex_match(str,reg);


    2.regex_replace(string s, regex e, string t),把s中匹配了e的子串替换为t

      regex reg("(colo)(u)(r)",boost::regex::icase|boost::regex::perl);
      string s="Colour,colour,color,colOurize";
      s=regex_replace(s,reg,"$1$3");


    t中的$n代表reg中的第n个括号里的内容,$3表示r,$1表示colo。上段代码表示把colour换成color,boost::regex::icase/boost::regex::perl是标志开关,表示忽略大小写。可以把需要的标志开关打开,不需要时默认关闭。

    regex_replace不修改原字符串,而是生成一个新串返回

    3.erase_all_regex(string, regex),(boost::algorithm::erase_all_regex,in header <boost/algorithm/string/regex.hpp>),删除满足regex的所有子串,它是在原串中直接修改

    #include <boost/algorithm/string/regex.hpp>
    erase_all_regex(str, boost::regex("[\n|\t|\r]"))

    删除字符串str中的所有空格

    4.split_regex(序列式容器, string, regex),(<boost/algorithm/string/regex.hpp>),分割符为regex格式,分割string,将结果存放在容器中

    #include <boost/algorithm/string/regex.hpp>
    vector<string> fields;
    split_regex( fields, str, boost::regex("[\\*|X]"));
    

    如果str = "5*6",fields中存放的是5和6。str不会被修改。

    5.split(序列式容器,string,Predicate), (<boost/algorithm/string/split.hpp>)。

    #include <boost/algorithm/string/split.hpp>
    #include <boost/algorithm/string/classification.hpp>
    vector<string> result;
    split(result, school_code, is_any_of(";"));

    is_any_of,用于判断school_code中是否包含";",以;分割school_code存放在result中,不修改原串。

  • 相关阅读:
    《将博客搬至CSDN》
    日志分析利器Splunk的搭建、使用、破解
    htop的安装和使用!
    centos下升级php5.3到php5.6
    TriAquae3.0部署安装
    Linux编译安装python2.7.5的步骤
    Centos 7.0 下安装 Zabbix server 3.0服务器的安装及 监控主机的加入(1)
    日志分析利器Splunk的搭建、使用、破解
    AIX上如何启动和停止系统服务
    Splunk日志服务器安装
  • 原文地址:https://www.cnblogs.com/whuqin/p/4982034.html
Copyright © 2011-2022 走看看