#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;
}
regex_replace()函数的应用与解析
最新推荐文章于 2024-07-23 11:38:21 发布