How to Replace Text in a String Using Regex in C++?
Regular expressions or what we can call regex for short are sequences of symbols and characters that create a search pattern and help us to find specific patterns within a given text. In this article, we will learn how to replace text in a string using regex in C++.
Example
Input: str = "Hello, World! Hello, GFG!" ; text = "Hello"; replace= "Hi"; Output: Hi, World! Hi, GFG!
Replace Regex Matches in C++ String
To replace a text in a string using regex, we can use the function std::regex_replace(). It is defined inside the <regex> header so we need to include it in our program.
Algorithm
1. Define the main string, string to be replaced and replacement string.
2. Create a regex object of the string you want to replace.
3. Then pass the main string, regex object and replacement string to the regex_replace() function.
4. The function regex_replace() returns a new string with the replacements applied.
C++ Program to Replace Text in a String Using Regex
C++
// C++ program to replace a pattern in a string using // regex. #include <iostream> #include <regex> #include <string> using namespace std; int main() { // target string string str = "Hello, World! Hello, GFG!" ; // Pattern string string pattern = "Hello" ; // regex object regex reg(pattern); // replacement string string replacement = "Hi" ; // call regex_replace() and store the result string result = regex_replace(str, reg, replacement); // Output the result cout << "Original: " << str << endl; cout << "Modified: " << result << endl; return 0; } |
Original: Hello, World! Hello, GFG! Modified: Hi, World! Hi, GFG!
Time Complexity: O(N)
Auxiliary Space: O(N)
Contact Us