In C++ how do I use regex to replace a string match
In C++11 the regex library was added which allows you to do regex directly:
#include <string> #include <regex> ... std::string workingOn("this text string\n"); std::regex expressionStart("^th"); std::string removed = std::regex_replace(workingOn, expressionStart,""); // removed will contain "is text string" std::regex expressionReplace("\\bte([^ ]*)"); // match word beginning with 'te' and grab everything to the end of it // which will be stored in $1 as the first captured match std::string replaced = std::regex_replace(workingOn, expressionReplace,"ve$1"); // replaced will contain "this vext string"
Also to search and capture just the matches:
std::smatch matches; // Match will contain: 1:Full string match, 2: Major, 3: Minor std::regex e("^Release ([1-9][0-9]*)"); std::string number; // Matches represent one match in the regex, but has all of the sub patterns // etc. and thus there are multiple matches for a single regex match... while (std::regex_search(test, matches, e)) { //matchingLine = matches[0]; number = matches[1]; break; } std::cout << "Number: " << number << std::endl;
Categories