words = ['honeysuck', 'suckle', 'HONEYSUCKER', 'honeysuckle']
EXCEPTIONS = ['honeysuckle']
def match_suck word
if (word =~ /suck/i) != nil
# should not match any of the exceptions
return true unless EXCEPTIONS.include? word.downcase
end
false
end
words.each{ |w|
puts "Testing match of '#{w}' : #{match_suck(w)}"
}
我相信你应该把你的异常放在一个不同的数组中,以防将来你想添加一个不同的规则。这将更容易阅读,并将在未来更快地改变,如果需要的话。在
我对Ruby的建议是:
您需要嵌套lookaround断言:
等效的解决方案是
suck(?!(?<=honeysuck)le)
。在下面是一个不使用正则表达式的解决方案:
现在:
^{pr2}$这对任何一个字符串都有效:
honeysuckle sucks
,this sucks
甚至regular expressions suck
。在相关问题 更多 >
编程相关推荐