Question

I'm trying to match the following examples (javascript):

1.- "dog dogs"
R- match dog = true

2.- "dogsdogs"
R- match dog= false

3.- "cat dog dogs dogdogs dog"
R - match dog(twice) = true

4.- "cat dog$dog"
R- match dog= false

5.- "cat dog\ndog" OR "cat dog\sdog"
R- match dog(twice) = true

6.- "catdog dog $dog$dog dog"
R- math dog(twice) = true

I've just got this /\b(dog)\b/g but if i use this /^(dog)$/g just match one word

Thanks in advance

Was it helpful?

Solution

Try this:

/(^|\s)(dog)(?=\s|$)/gm

Tested via regexr - http://regexr.com?38gla

This matches a start of string or whitespace, then the word dog, then whitespace or end of string. The trailing whitespace/end of string is a positive lookahead, so its not consumed, allowing that space to be used for another match - ex "cat dog dog"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top