Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript RegEx excluding certain word/phrase?

How can I write a RegEx pattern to test if a string contains several substrings with the structure:

"cake.xxx"

where xxx is anything but not "cheese" or "milk" or "butter".

For example:

  • "I have a cake.honey and cake.egg" should return true, but
  • "I have a cake.**milk** and cake.egg" should return false.
like image 407
vantrung -cuncon Avatar asked Oct 06 '11 12:10

vantrung -cuncon


People also ask

How do you exclude a word in regex?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself. The character '.

What is ?! In regex?

The ?! n quantifier matches any string that is not followed by a specific string n.

How do you skip special characters in regex?

for metacharacters such as \d (digit), \D (non-digit), \s (space), \S (non-space), \w (word), \W (non-word). to escape special regex characters, e.g., \. for . , \+ for + , \* for * , \? for ? . You also need to write \\ for \ in regex to avoid ambiguity.

What is \b in regex JavaScript?

The RegExp \B Metacharacter in JavaScript is used to find a match which is not present at the beginning or end of a word. If a match is found it returns the word else it returns NULL. Example 1: This example matches the word “for” which is not present at the beginning or end of the word.


1 Answers

Is it this what you want?

^(?!.*cake\.(?:milk|butter)).*cake\.\w+.*

See it here on Regexr

this will match the complete row if it contains a "cake.XXX" but not when its "cake.milk" or "cake.butter"

.*cake\.\w+.* This part will match if there is a "cake." followed by at least one wrod character.

(?!.*cake\.(?:milk|butter)) this is a negative lookahead, this will prevent matching if the string contains one of words you don't allow

^ anchor the pattern to the start of the string

like image 117
stema Avatar answered Oct 14 '22 00:10

stema