C++中的ReExxId替换使用ReExxId替换字符串的匹配

std::regex_replace() 用于替换字符串中的所有匹配项,

null

语法:

regex_replace(subject, regex_object, replace_text)

参数: 它接受以下三个参数:

  1. 主题字符串作为第一个参数。
  2. regex对象作为第二个参数。
  3. 替换文本作为第三个参数的字符串。

返回值: 函数返回应用了替换项的新字符串。

  1. $或$0用于插入整个正则表达式匹配项。
  2. $1,$2,……最多$9用于插入前九个捕获组匹配的文本。
  3. $`(回勾)用于插入匹配项左侧的字符串。
  4. $’(引号)用于插入匹配项右侧的字符串。
  5. 如果捕获组的数量小于请求的数量,则将被零替换。

例如: 假设一个正则表达式对象 re(((极客)(*)) 已创建,主题字符串为: 主题(“关于极客的一切”) ,则要用任何 捕获组 (例如:0美元,1美元,最多9美元)。

示例1: 将匹配内容替换为$1。 这里匹配的是“Geeksforgeks”,将被1美元(“geeks”)取代。 因此,结果“全是极客”。

例2: 将匹配内容替换为$2。 这里匹配的是“Geeksforgeks”,它将被2美元(“forgeks”)取代。 因此,结果“全是伪造的”。

下面是显示regex_replace工作的程序。

// C++ program to show the working
// of regex_replace
#include <bits/stdc++.h>
using namespace std;
int main()
{
string subject( "its all about geeksforgeeks" );
string result1, result2, result3, result4;
string result5;
// regex object
regex re( "(geeks)(.*)" );
// $2 contains, 2nd capturing group which is (.*) means
// string after "geeks" which is "forgeeks". hence
// the match(geeksforgeeks) will be replaced by "forgeeks".
// so the result1 = "its all about forgeeks"
result1 = regex_replace(subject, re, "$2" );
// similarly $1 contains, 1 st capturing group which is
// "geeks" so the match(geeksforgeeks) will be replaced
// by "geeks".so the result2 = "its all about geeks".
result2 = regex_replace(subject, re, "$1" );
// $0 contains the whole match
// so result3 will remain same.
result3 = regex_replace(subject, re, "$0" );
// $0 and $& contains the whole match
// so result3 will remain same
result4 = regex_replace(subject, re, "$&" );
// Here number of capturing group
// is 2 so anything above 2
// will be replaced by nothing.
result5 = regex_replace(subject, re, "$6" );
cout << result1 << endl << result2 << endl;
cout << result3 << endl << result4 << endl
<< result5;
return 0;
}


输出:

its all about forgeeks
its all about geeks
its all about geeksforgeeks
its all about geeksforgeeks
its all about

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享