std::regex_replace() is used to replace all matches in a string,
regex_replace(subject, regex_object, replace_text)
Parameters: It accepts three parameters which are described below:
- Subject string as the first parameter.
- The regex object as the second parameter.
- The string with the replacement text as the third parameter.
Return Value: Function returns a new string with the replacements applied.
- $& or $0 is used to insert the whole regex match.
- $1, $2, … up to $9 is used to insert the text matched by the first nine capturing groups.
- $` (back-tick) is used to insert the string that is left of the match.
- $’ (quote) is used to insert the string that is right of the match.
- If number of capturing group is less than the requested, then that will be replaced by nothing.
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).
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”.
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.
its all about forgeeks its all about geeks its all about geeksforgeeks its all about geeksforgeeks its all about
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Program to find all match of a regex in a string
- std::string::replace , std::string::replace_if in C++
- Count elements in a vector that match a target value or condition
- std::replace and std::replace_if in C++
- Replace each node with its Surpasser Count in Linked List
- Rust vs C++: Will Rust Replace C++ in Future ?
- std::string::crbegin() and std::string::crend() in C++ with Examples
- Check if a string can be formed from another string using given constraints
- std::string::append vs std::string::push_back() vs Operator += in C++
- std::string::remove_copy(), std::string::remove_copy_if() in C++
- std::string::replace_copy(), std::string::replace_copy_if in C++
- Periodic Binary String With Minimum Period and a Given Binary String as Subsequence.
- string at() in C++
- std::string::erase in C++
- std::string::clear in C++
- std::string::compare() in C++
- std::string::insert() in C++
- std::string::resize() in C++
- std::string::append() in C++
- std::string::assign() in C++