Skip to content Skip to sidebar Skip to footer

Regex That Matches A Pattern And Doesn't Match Specific Words

I have my basic javascript regex for any string containing at least one alphabet: ^(.*[A-Za-z]+.*)+ Now I want to update this regex so it won't match the following words: 'n\a' an

Solution 1:

(?!) is actually a negative lookahead. But you are correct that it holds the key here:

^(?!n\\a$)(?!none$)(.*[A-Za-z].*)

Basically, starting at the beginning (^) we want to ensure that til the end ($) the string does not consist solely of these two.

To make this case insensitive, you can just add the i regex flag:

'NONE'.match(/^(?!n\\a$)(?!none$)(.*[A-Za-z].*)/)  //=> ["NONE", "NONE"]
'NONE'.match(/^(?!n\\a$)(?!none$)(.*[A-Za-z].*)/i) //=>null

See it in action

Also note that your original regex didn't need the +s as matching one already ensures the presence of at least one.

Post a Comment for "Regex That Matches A Pattern And Doesn't Match Specific Words"