Z-Mehn
Z-Mehn

Reputation: 268

Regex: Find specific string as long as it occurs before another specific string

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

Answers (2)

jwismar
jwismar

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

Ben Smith
Ben Smith

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

Related Questions