Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, how can I use regex to match unless words are in a list of excluded words?

How do I use regex to match any word (\w) except a list of certain words? For example:

I want to match the words use and utilize and any words after it except if the words are something or fish.

use this  <-- match
utilize that  <-- match
use something   <-- don't want to match this
utilize fish <-- don't want to match this

How do I specify a list of words I don't want to match against?

like image 600
Jake Wilson Avatar asked Jan 13 '12 17:01

Jake Wilson


2 Answers

You can use a negative lookahead to determine that the word you are about to match is not a particular thing. You can use the following regex to do this:

(use|utilize)\s(?!fish|something)(\w+)

This will match "use" or "utilize" followed by a space, and then if the following word is not "fish" or "something", it will match that next word.

like image 88
murgatroid99 Avatar answered Oct 25 '22 19:10

murgatroid99


This should do it:

/(?:use|utilize)\s+(?!something|fish)\w+/
like image 24
Cfreak Avatar answered Oct 25 '22 17:10

Cfreak