AlreadyLost
AlreadyLost

Reputation: 827

regex to find string that has two key words but does not include a 3rd one

Can someone help me to build a regex to find a string that has keyword1 and keyword2 but not keyword3?

I tried this but didn't work:

/^(?=.*\bkeyword1\b)(?=.*\bkeyword2\b)(?:(?!:keyword3)).*$/,

many thanks

Upvotes: 0

Views: 47

Answers (1)

Peter Thoeny
Peter Thoeny

Reputation: 7616

Use two positive lookaheads and one negative lookahead:

[
  'has keyword1 and keyword2 and not 3.',
  'has keyword2 and keyword1 and not 3.',
  'has keyword1 and keyword2 and keyword3.',
  'has keyword3 and keyword2 and keyword1.',
  'has keyword4 and keyword5 but not 1 and 2'
].forEach(str => {
  let m = str.match(/^(?=.*\bkeyword1\b)(?=.*\bkeyword2\b)(?!.*\bkeyword3\b)./);
  console.log(str + ' => ' + (m ? true : false))
});
output:

has keyword1 and keyword2 and not 3. => true
has keyword2 and keyword1 and not 3. => true
has keyword1 and keyword2 and keyword3. => false
has keyword3 and keyword2 and keyword1. => false
has keyword4 and keyword5 but not 1 and 2 => false

Explanation:

  • ^ -- anchor at start of string
  • (?=.*\bkeyword1\b) -- positive lookahead for keyword1 anywhere in the string
  • (?=.*\bkeyword2\b) -- positive lookahead for keyword2 anywhere in the string
  • (?!.*\bkeyword3\b) -- negative lookahead for keyword3 anywhere in the string
  • . -- any single character (to avoid falsy test on empty string)

Upvotes: 2

Related Questions