how to use Boost regular expression replace method?

unwise guy picture unwise guy · Jul 4, 2012 · Viewed 22.3k times · Source

I have these variables:

boost::regex re //regular expression to use
std::string stringToChange //replace this string
std::string newValue //new value that is going to replace the stringToChange depending on the regex.

I only want to replace the first occurrence of it only.

Thanks fellas.

EDIT: I've found this:

boost::regex_replace(stringToChange, re, boost::format_first_only);

but it says the function does not exists, I'm guessing the parameters are incorrect at the moment.

Answer

Jesse Good picture Jesse Good · Jul 4, 2012

Here is an example of basic usage:

#include <iostream>
#include <string>
#include <boost/regex.hpp>

int main(){
  std::string str = "hellooooooooo";
  std::string newtext = "o Bob";
  boost::regex re("ooooooooo");
  std::cout << str << std::endl;

  std::string result = boost::regex_replace(str, re, newtext);
  std::cout << result << std::endl;
}

Output

hellooooooooo

hello Bob

Make sure you are including <boost/regex.hpp> and have linked to the boost_regex library.