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中,不修改原串。

 

转载于:https://www.cnblogs.com/whuqin/archive/2012/09/19/4982034.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值