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
.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 '.
The ?! n quantifier matches any string that is not followed by a specific string n.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With