3

I'm trying to write a regex to blacklist certain words. I'm able to create a whitelist like /^(carrots|onions|corn)$/ but how would I convert that into a blacklist?

Edit: To clarify, I'm matching this blacklist against a whole string. For example "corndog" should be allowed. I want the regex equivalent of blacklistArray.indexOf(word) === -1

ryanve
  • 50,076
  • 30
  • 102
  • 137
  • 1
    check this one http://stackoverflow.com/questions/7801581/regex-for-string-not-containing-multiple-specific-words – Mils Apr 26 '17 at 18:03
  • Thanks—that's similar but different. Please see clarified question and unmark as duplicate if possible. – ryanve Apr 28 '17 at 21:07
  • @wiktor-stribiżew can you please reopen? This is not a duplicate. – ryanve May 08 '17 at 21:36
  • @ryanve: It ***is*** a dupe. See my answer there, (match everything but) *a string equal to some string* section. Your solution: `^(?!(?:carrots|onions|corn)$)` - it will match any string not equal to `carrots`, `onoins`, `corn`. – Wiktor Stribiżew May 08 '17 at 21:57
  • @WiktorStribiżew Mine is about matching whole words not subwords. My coworker figured out that the correct pattern for this is https://gist.github.com/ryanve/004dcaecf1fe4835345385b4d1500c78 Yours is different and not what I asked for in the question. Again, please reopen as this is valuable to the community. – ryanve May 09 '17 at 16:48
  • The `/^(?!(corn|bread)$).+/.test('corn')` code is equal to `/^(?!(corn|bread)$)/.test('corn')`, just `.+` requires at least char. – Wiktor Stribiżew May 09 '17 at 17:29
  • The `.+` makes it diffferent. Please reopen. – ryanve May 09 '17 at 17:54

1 Answers1

4

Use negative lookahead:

^(?!.*(?:carrots|onions|corn))
chazsolo
  • 7,873
  • 1
  • 20
  • 44
  • That feels close but it also seems to blacklist partial matches. I only want to blacklist exact matches. `/^(?!.*(?:carrots|onions|corn))/.test('corndog')` is false where I'd want that to be true to allow corndog. – ryanve Apr 27 '17 at 00:02