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

 

posted @ 2012-09-19 19:16  春文秋武  阅读(1524)  评论(0编辑  收藏  举报