无法使我的 Ruby 负面展望正则表达式正常工作

Unable to get my Ruby negative look ahead regex to work properly

我正在使用 Ruby 2.4。我想在字符串中搜索一个词,但前提是它前面没有另一个词。我想我可以使用这种负面的前瞻性,如下所示,但是如果 "bad" 这个词是"apple" 之前。 "bad" 和 "apple."

之间只有一个 space
2.4.0 :014 > word_regex = /(?!.*bad)(^|\s)#{Regexp.escape(word)}(\s|$)/i
 => /(?!.*bad)(^|\s)apple(\s|$)/i
2.4.0 :015 > "good apple".match(word_regex)
 => #<MatchData " apple" 1:" " 2:"">
2.4.0 :016 > "bad apple".match(word_regex)
 => #<MatchData " apple" 1:" " 2:"">

我还缺少什么?

考虑像这样使用负向回顾 (?<!bad\s)apple 将仅在 bad 前面没有时才查找 apple。注意 bad.

之后的 space

Regex101 Demo

我试过了,就像@sagarpandy82 说的那样

word_regex = /(?<!bad)(^|\s)#{Regexp.escape("apple")}(\s|$)/i
a = "good apple".match(word_regex)
b = "bad apple".match(word_regex)

但是,等等,否定前瞻可以是可变长度!

R = /
    \b                 # match word break
    #{'apples'.reverse} # match 'elppa'
    \b                 # match word break
    (?!                # begin a negative lookahead
      \s+              # match one or more whitespaces
      #{'bad'.reverse} # match 'dab'
      \b               # match word break
    )                  # close negative lookaheaad
    /ix                # case-indifferent and free-spacing regex definition modes
#=> /
    \b                 # match word break
    elppa              # match 'selppa'
    \b                 # match word break
    (?!                # begin a negative lookahead
      \s+              # match one or more whitespaces
      dab              # match 'dab'
      \b               # match word break
    )                  # close negative lookaheaad
    /x

def avoid_bad_apples(str)
  str.reverse.match? R
end

avoid_bad_apples("good apples")           #=> true
avoid_bad_apples("Simbad apples")         #=> true
avoid_bad_apples("bad pears")             #=> false
avoid_bad_apples("bad apples")            #=> false
avoid_bad_apples("bad    apples")         #=> false
avoid_bad_apples("good applesauce")       #=> false
avoid_bad_apples("Very bad apples. BAD!") #=> false