Search code examples
c++regexboost-regex

Replace all matches in 1 iteration using regular expressions


Is it possible to search different patterns and replace the matchings in 1 iteration?

For example, if I have the string

"Hey {Apple}, where is {Carrots|Peas|Cucumber}?"

Is it possible to replace everything inside the curly braces in 1 iteration so that it looks like:

"Hey fruit, where is vegetables?

The reason I ask is because my current implementation first searches all patterns that only have one value inside the curly braces (1-iteration), and then it searches for the curly braces with 3 values right after (2-iterations), thus taking x-amount of iterations, where x = "{}".

Thanks guys, I hope this makes sense.


Solution

  • This isn't really a regex issue, since doing replacements in a string is outside the scope of regular expressions.

    That said, it depends on the variety of the patterns. If you have a relatively small set of patterns, then you could set up a Map from string to replacement, and just have your output iterator look up the replacement value for each match it gets.

    For instance, "Apple" would map to "Fruit", and "Carrots" would map to "vegetables", and "Peas" would also map to "vegetables", etc.