VOOZH about

URL: https://www.geeksforgeeks.org/cpp/regex_replace-in-cpp-replace-the-match-of-a-string-using-regex_replace/

⇱ regex_replace in C++ | Replace the match of a string using regex_replace - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

regex_replace in C++ | Replace the match of a string using regex_replace

Last Updated : 11 Jul, 2025
std::regex_replace() is used to replace all matches in a string, Syntax:
regex_replace(subject, regex_object, replace_text)
Parameters: It accepts three parameters which are described below:
  1. Subject string as the first parameter.
  2. The regex object as the second parameter.
  3. The string with the replacement text as the third parameter.
Return Value: Function returns a new string with the replacements applied.
  1. $& or $0 is used to insert the whole regex match.
  2. $1, $2, ... up to $9 is used to insert the text matched by the first nine capturing groups.
  3. $` (back-tick) is used to insert the string that is left of the match.
  4. $' (quote) is used to insert the string that is right of the match.
  5. If number of capturing group is less than the requested, then that will be replaced by nothing.
Examples: Suppose a regex object re("(geeks)(.*)") is created and the subject string is: subject("its all about geeksforgeeks"), you want to replace the match by the content of any capturing group (eg $0, $1, ... upto 9).
Example-1: Replace the match by the content of $1. Here match is "geeksforgeeks" that will be replaced by $1("geeks"). Hence, result "its all about geeks". Example-2: Replace the match by the content of $2. Here match is "geeksforgeeks" that will be replaced by $2("forgeeks"). Hence, result "its all about forgeeks".
Below is the program to show the working of regex_replace.
Output:
its all about forgeeks
its all about geeks
its all about geeksforgeeks
its all about geeksforgeeks
its all about
Comment
Article Tags:
Article Tags: