-1

So I'm trying to match all the instances of the word "test" exactly in a given text, and I'm using the following regex:

/(^|\s)test(\s|\.|$|,|!|\?|;|¿|¡)/gi

It works when the text is something like "this is a test. How is the test going? test." However, when you have two or more consecutive "test"'s it does not work.

ie:

var regex = /(^|\s)test(\s|\.|$|,|!|\?|;|¿|¡)/gi;
"test test test".match(regex); 
//returns only ["test", "test"], should be ["test", "test", "test"]

What can I do to make the regex work with consecutive words?

janedoe
  • 907
  • 1
  • 13
  • 33

2 Answers2

1

The second test is missing because the space character is consumed when matching the first test pattern; You can change the second parenthesis to look ahead so it doesn't consume characters:

var regex = /(?:^|\s)test(?=\s|\.|$|,|!|\?|;|¿|¡)/gi;
console.log("test test test".match(regex)); 
Psidom
  • 209,562
  • 33
  • 339
  • 356
1

I'm not sure if this is what you're looking for, but this regex :

(?<=\W)test(?=\W)

will match any test word preceded and followed by a non word character. This way, it wont match "testtest" for example.

See Regex101.com

Edit : I am surprised to discover that lookbehind assertions aren't supported in JavaScript apparently (see here for example). I think in your case the best regex would be the one suggested in the comments : \btest\b.

Paul-Etienne
  • 796
  • 9
  • 23
  • I just tried this and it's saying invalid regular expression unfortunately. – janedoe Oct 27 '17 at 01:22
  • I've just edited my answer, apparently lookbehind assertions aren't supported in JS. But you've got one working with the chosen answer anyway, so all good. – Paul-Etienne Oct 27 '17 at 07:26