-1

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" and "none". Containing them is valid, meaning "n\aa" or "nn\a" are valid, and just words that are an exact match to the words I don't want will cause regex not to match.

I saw that many examples to words not containing specific string using negative lookbehind like

^(?!.*bar).*$

but I wasn't able to transform it to work with exact match.

ndnenkov
  • 35,425
  • 9
  • 72
  • 104
Rotem B
  • 1,327
  • 1
  • 15
  • 20
  • Try `^(\bn/a\b|\bnone\b)` – kiner_shah Dec 13 '16 at 08:08
  • Try `/^(?![\s\S]*\b(?:n\\a|none)\b)[^a-z]*[a-z][\s\S]*$/i` – Wiktor Stribiżew Dec 13 '16 at 08:13
  • do you want to match the words or to just test/validate ? – RomanPerekhrest Dec 13 '16 at 08:16
  • *containing at least one alphabet* An [alphabet](https://en.wikipedia.org/wiki/Alphabet) is a set of written symbols used to write a language, such as the Roman alphabet used to write English. You mean "letter" or "alphabetic character". With regard to your regexp, I'm not sure what the `^` and parentheses and `.*` all mean--it is exactly equivalent to writing `/a-z/i`. By the way, what do you mean by `\a`? Do you mean a literal backslash followed by an "a"? –  Dec 13 '16 at 11:46

1 Answers1

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.

ndnenkov
  • 35,425
  • 9
  • 72
  • 104