Replacing strings

The regex_replace method is similar to the other methods in that it takes a string (a C string or C++ string object, or iterators to a range of characters), a regex object, and optional flags. In addition, the function has a format string and returns a string. The format string is essentially passed to the format method of each results_match object from the result of the matches to the regular expression. This formatted string is then used as the replacement for the corresponding matched substring. If there are no matches, then a copy of the searched string is returned.

    string str = "use the list<int> class in the example"; 
regex rx("b(list)(<w*> )");
string result = regex_replace(str, rx, "vector$2");
cout << result << "n"; // use the vector<int> class in the example

In the preceding code, we say that the entire matched string (which should be list< followed by some text followed by > and a space) should be replaced with vector, followed by the second sub match (< followed by some text followed by > and a space). The result is that list<int> will be replaced with vector<int>.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset