Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx to match all occurrences of a character *after* the first occurrence?

For instance if I am trying to match 'w's in the input string

edward woodward

the two 'w's in the second word should be matched, not the one in the first word.

I have an inkling the solution might involve 'negative lookbehind' but just can't get any working solution.

(I am working with Objective C and the regex replace methods on NSMutableString but I would also be happy to hear about solutions for any regex implementation.)

like image 880
Jim Blackler Avatar asked Dec 06 '22 21:12

Jim Blackler


1 Answers

Your problem is that you'd need not just lookbehind (which some regex flavors don't support at all) but infinite repetition inside the lookbehind assertion (which only very few flavors support, like .NET for example).

Therefore, the .NET- or JGSoft-compatible regex

(?<=w.*)w

won't work in Objective C, Python, Java, etc.

So you need to do it in several steps: First find the string after the first w:

(?<=w).*

(if you have lookbehind support at all), then take the match and search for w inside that.

If lookbehind isn't supported, then search for w(.*) and apply the following search to the contents of the capturing group 1 ($1).

like image 116
Tim Pietzcker Avatar answered May 20 '23 05:05

Tim Pietzcker