Skip to content

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

C++

TheSoftwareProgrammer View All

I like science and writing software.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: