regex_replace()函数的应用与解析

#include<string>
#include<regex>
#include<iostream>
using namespace std;
int main(int argc, char argv[])
{
	string str = "this is a subsquence in the string";
	regex reg("(sub)([\\w]+)");
	//该正则表达式匹配sub开头的子字符串
	//regex_replace(std::string str,std::regex reg,std::string replace)为regex_replace()六中格式中的一种
	//他的返回值是std::string,所以在下面的语句中可以输出,执行替换规则之后的string
	cout << regex_replace(str, reg, "sub-$2") << endl;
	//更换匹配规则
	cout << regex_replace(str, reg, "$2") << endl;
	//regex_replace()有六中不同的重载函数,在这里书写的是regex_replace(OutIterator out,std::string str.begin(),
	//std::string str.end(),std::regex reg,std::string format)
	//在该函数中,匹配结果最终存入OutIterator out中
	string result;
	regex_replace(back_inserter(result), str.begin(), str.end(), reg, "$1 and $2");
	//back_inserter()的作用相等于是string::push_back(),将匹配之后的结果输入到result中
	//他的返回值是back_inserter_iterator
	cout << result << endl;
	cout << regex_replace(str, reg, "$2", regex_constants::format_no_copy) << endl;
	//在该函数语句中regex_constants::format_no_copy的意义是在匹配之后的结果中,只有替换的部分
	//在该函数中是会输出第二个捕捉组的内容,而不包含其他的内容
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值