4

I tried to write a method which acts like Java's Matcher::replaceFirst(String replacement). I know how to replace all matches in a std::string, with std::regex_replace, but how can I only replace the first match of a regex in a string?

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
Exagon
  • 4,798
  • 6
  • 25
  • 53

2 Answers2

6

You can use std::regex_replace with an additional flag, std::regex_constants::format_first_only, to get the result you want.

Take a look at http://en.cppreference.com/w/cpp/regex/regex_replace for additional information.

Moreira
  • 576
  • 2
  • 8
1

You can still use std::regex_replace by specifying format_first_only as an argument to the flag parameter of std::regex_replace().

Look here http://en.cppreference.com/w/cpp/regex/match_flag_type

Biruk Abebe
  • 2,235
  • 1
  • 13
  • 24