14

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.

unwise guy
  • 1,048
  • 8
  • 18
  • 27

1 Answers1

37

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.

Community
  • 1
  • 1
Jesse Good
  • 50,901
  • 14
  • 124
  • 166