[英]Unable to get my Ruby negative look ahead regex to work properly
我正在使用Ruby 2.4。 我想搜索字符串中的单词,但前提是没有另一个单词出现在单词之前。 我以为可以使用这种否定的预见方式,如下所示,但是如果“坏”一词位于“苹果”之前,但我不想完成比赛时,我仍然可以找到短语“坏苹果” ”。 不能认为单词“坏”和单词“苹果”之间只有一个空格。
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:"">
我还想念什么?
但是,等等,否定的前瞻可以是可变长度!
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
考虑使用像这样的否定式后向(?<!bad\\s)apple
apple仅在不以bad
开头的情况下才寻找apple 。 注意空格bad
。
我试了一下,就像@ sagarpandy82所说的那样
word_regex = /(?<!bad)(^|\s)#{Regexp.escape("apple")}(\s|$)/i
a = "good apple".match(word_regex)
b = "bad apple".match(word_regex)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.