0

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.

Robert
  • 8,717
  • 2
  • 27
  • 34
unwise guy
  • 1,048
  • 8
  • 18
  • 27
  • Your best bet would be to search the document for your string. Then extract the portion of the string that matches, and then go in and replace what you want on the presumably much shorter string. – Falmarri Jul 05 '12 at 23:52
  • Yes, that is what I'm currently doing, but the problem arises when searching for the string. I search the string by looking for "{" and "}", however, if carrots contain curly braces within themselves... {{Carrots}|Peas|Cucumber}, Carrots would be replaced two times when it should only be replaced once, "{vegetables}" – unwise guy Jul 05 '12 at 23:57
  • that's why I want to replace all matchings in 1 iteration rather than searching and searching. – unwise guy Jul 05 '12 at 23:58
  • So you want to replace any {} with a real vegetable name in the brackets with "vegetable", and the {} with fruit names with the word "fruit"? Of do you just replace every {} with _one_ item inside with "fruit", and {} with multiply items inside with "vegetable"? – SingerOfTheFall Jul 06 '12 at 05:20

1 Answers1

2

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.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175