2

std::regex_replace (Added in C++ 11) replaces all the occurrences. How can I make it replace only the first occurrence?

0

2 Answers 2

14

If the flags parameter to std::regex_replace contains std::regex_constants::format_first_only, only the first match is replaced.

std::regex_replace("12 34",
                   std::regex(R"(\d+)"),
                   "num",
                    std::regex_constants::format_first_only);

stribizhev kindly provided a working example.

Sign up to request clarification or add additional context in comments.

3 Comments

I was writing it as I did not want to post without an example :( Here is the snippet.
regex_replace("231 is my string 1", regex("\\d+"), string("number"), std::tr1::regex_constants::format_first_only);
@stribizhev Thank you, I feel sorry for you put in more effort.
2

I found the solution myself. Posting for others if they face the same issue. Add:

std::tr1::regex_constants::format_first_only

to replace only the first occurrence as the fourth argument to regex_replace

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.