Reputation: 268
Yep, another regex (javascript implementation) question...
I can't figure out how to find the string 'cat' as long as it occurs anywhere ahead of 'dog'.
So for the following sentence...
cat categorically hates the dog, im going to mention cat again.
The first and second occurrences will be found, not the last one.
Upvotes: 1
Views: 359
Reputation: 12258
You need to use a lookahead:
/cat(?=.*dog)/
matches any "cat" that is followed anywhere by a "dog", taking into account that there may be other characters in between.
Upvotes: 3
Reputation: 20230
Your questions states:
I can't figure out how to find the word 'cat' as long as it occurs anywhere ahead of 'dog'.
The regular expression for this is:
cat(?!.*dog)
This uses negative lookup to find cat which is not followed by dog.
Upvotes: 0