📜  C++中的regex_replace |使用regex_replace替换字符串的匹配项

📅  最后修改于: 2021-05-30 13:57:14             🧑  作者: Mango

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

句法:

regex_replace(subject, regex_object, replace_text)

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

  1. 主题字符串作为第一个参数。
  2. 正则表达式对象作为第二个参数。
  3. 以替换文本作为第三个参数的字符串。

返回值:函数返回一个新的字符串,其中包含替换内容。

  1. $&或$ 0用于插入整个正则表达式匹配项。
  2. $ 1,$ 2,…最多$ 9用于插入与前9个捕获组匹配的文本。
  3. $`(反引号)用于插入匹配项左侧的字符串。
  4. $’(引号)用于插入匹配项右边的字符串。
  5. 如果捕获组的数量小于请求的数量,则将其替换为任何内容。

例子:
假设创建了一个正则表达式对象re(“(geeks)(。*)”) ,并且主题字符串为: subject(“关于geeksforgeeks的全部”) ,您希望将匹配项替换为任何捕获组的内容(例如$ 0)。 ,$ 1,…最多9)。

下面是显示regex_replace的程序。

// C++ program to show the working
// of regex_replace
#include 
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
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”