Regexp - finding first word in a group of repeating words after a particular word

53 views Asked by At

I have a string "Foo Bar Foo Bar", I want to select the first Bar in that string

At the moment I have: http://regexr.com?37mv1 which is not quite right

This is the first Foo 'Bar' I ever had in Foo Bar. 'Bar' should be picked up.....Hope it makes sense

1

There are 1 answers

0
Casimir et Hippolyte On

you can use this:

^.*?Foo\s*(Bar)

or more simple:

^.*?(Bar)

or more efficient (with long strings):

^(?>[^F]++|F(?!oo))*Foo\s*(Bar)

The problem of your pattern is the first greedy quantifier .*. This subpattern will match all possible character until the end of the string/line, then the regex engine must go back character by character until it find Foo, but the Foo it find is the last.

A lazy quantifier .*? will check for each characters if Foo follows.

Note: you can uncheck the i and g checkboxes in gskinner.