Jim Blackler
Jim Blackler

Reputation: 23169

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.)

Upvotes: 4

Views: 7449

Answers (2)

Bart Kiers
Bart Kiers

Reputation: 170158

To replace every N-th "w" (where N > 1) with an "X" for example, you could search for the pattern:

(?<=w)(.*?)w

and replace it with:

$1X

Upvotes: 5

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

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).

Upvotes: 11

Related Questions