正则表达式匹配包含 'apple' 但不匹配同一字符串中的 'orange' 的字符串

RegExp to match string that includes 'apple' but does not match 'orange' in same string

给定以下数据

green-pineapple-bird
red-apple-dog  
blue-apple-cat  
green-apple-orange-horse  
green-apple-mouse  

我想弄清楚如何让 (Javascript) RegExp.test() 匹配任何包含单词 "apple" 的条目(任何地方)但不匹配任何条目包含单词 "orange" (任何地方)。结果列表将是:

red-apple-dog  
blue-apple-cat  
green-apple-mouse  

我在数据中加入了破折号只是为了便于阅读。实际数据可能包含也可能不包含破折号。

如果我试试这个:

/^(?!orange).*(apple).*/gm

使用 https://regex101.com/ 它匹配所有行。

我尝试使用 JavaScript RegEx excluding certain word/phrase? 作为灵感:

/^(?!.*apple\.(?:orange|butter)).*apple\.\w+.*/gm

如果有不同,我正在使用 Mozilla Rhino 1.7R4。

对于apple中的每个字符not(在之后),你需要对orange。因为您不希望 pineapple 匹配,所以您还应该在 apple:

周围放置单词边界

const re = /^((?!orange).)*\bapple\b((?!orange).)*$/;
`green-pineapple-bird
red-apple-dog  
blue-apple-cat  
green-apple-orange-horse  
green-apple-mouse`
  .split('\n')
  .forEach(str => {
    console.log(re.test(str) + ' ' + str)
  });