Boost(五)——字符串处理(二):正则表达式操作

正则表达式:

一些简单的描述符:

. 匹配除换行符以外的任意字符

\w 匹配字母或数字或下划线或汉字 等价于 '[^A-Za-z0-9_]'。

\s 匹配任意的空白符

\d 匹配数字

\b 匹配单词的开始或结束

^ 匹配字符串的开始

$ 匹配字符串的结束

一、字符串与正则表达式的比较

正则匹配: \\w+\\s\\w+ 形式(w+ 与w差不多 ,“+”意义:至少匹配一次)

std::string s = "hello world";
boost::regex expr("\\w+\\s\\w+");
boost::regex_match(s, expr); 

二、字符串中搜索正则表达式

std::string s = "hello world";
boost::smatch what;
boost::regex expr("\\w+\\s\\w+");
boost::regex_search(s, what, expr); 

 存储结果的类 boost::smatch(boost::match_results<string::const_iterator>)事实上是持有类型为 boost::sub_match 的元素的容器。

boost::regex_search()函数将正则搜索结果写入 v中

boost::match_results类内部重载了"[]"运算符,能用下标法读取。

std::string s = "hello world";
boost::smatch what;
boost::match_results<string::const_iterator> v;
boost::regex expr("(\\w+)\\s(\\w+)");
if (boost::regex_search(s, v, expr))
{
	cout << v.size() << endl;
	cout << v[0] << endl;
	cout << v[1] << endl;
}

就算越界也没事。

三、正则表达式替换字符串

string s = "hello world";
boost::regex expr("(\\w+)\\s(\\w+)");
string fmt = "_";
boost::regex_replace(s, expr, fmt); //输出结果是hello_world

互换位置:

string s = "hello world";
boost::regex expr("(\\w+)\\s(\\w+)");
string fmt = "\\2 \\1";
boost::regex_replace(s, expr, fmt); //输出结果是world hello

 boost::regex_constants::format_literal 标志作为第四参数传递给函数 boost::regex_replace() ,从而抑制了格式参数中对特殊字符的处理。

string s = "hello world";
boost::regex expr("(\\w+)\\s(\\w+)");
string fmt = "\\2 \\1";
boost::regex_replace(s, expr, fmt, boost::regex_constants::format_literal); //输出结果是\2 \1

boost::algorithm::find_regex() 、 boost::algorithm::replace_regex() 、 boost::algorithm::erase_regex() 以及 boost::algorithm::split_regex() 等等与boost::regex_...形式类似

例如:

boost::algorithm::replace_regex(s, expr, fmt);//直接修改了s字符串
cout << boost::algorithm::find_regex(s, expr) << endl;
boost::algorithm::erase_regex(s, expr);//直接修改了s字符串
vector<string> v;
boost::algorithm::split_regex(v, s, expr);//用容器存储分割结果

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值