正则表达式匹配(如果不是在和之前)

2024-05-03 18:33:03 发布

您现在位置:Python中文网/ 问答频道 /正文

如果不是“金银花”的一部分,我怎么能匹配“烂”?在

使用lookbehind和lookahead,我可以匹配suck,如果不是“honeysuck”或“suckle”,但它也无法捕捉到“honeypuck”之类的内容;这里的表达式应该匹配,因为它不以le结尾:

re.search(r'(?<!honey)suck(?!le)', 'honeysucker')

Tags: rele内容search表达式结尾honeylookahead
3条回答

我相信你应该把你的异常放在一个不同的数组中,以防将来你想添加一个不同的规则。这将更容易阅读,并将在未来更快地改变,如果需要的话。在

我对Ruby的建议是:

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)}"
}

您需要嵌套lookaround断言:

>>> import re
>>> regex = re.compile(r"(?<!honey(?=suckle))suck")
>>> regex.search("honeysuckle")
>>> regex.search("honeysucker")
<_sre.SRE_Match object at 0x00000000029B6370>
>>> regex.search("suckle")
<_sre.SRE_Match object at 0x00000000029B63D8>
>>> regex.search("suck")
<_sre.SRE_Match object at 0x00000000029B6370>

等效的解决方案是suck(?!(?<=honeysuck)le)。在

下面是一个不使用正则表达式的解决方案:

s = s.replace('honeysuckle','')

现在:

^{pr2}$

这对任何一个字符串都有效:honeysuckle sucksthis sucks甚至regular expressions suck。在

相关问题 更多 >