rex = r'today.*?monday (?!night)'
txt = 'today [blah blah] monday night but [blah blah] monday morning'
m = re.search(rex, txt)
这可能只分2个阶段,但我只对“星期一”的第一个实例感兴趣。所以在这种情况下我希望re.search()返回None。而不是它继续到第二个星期一'发现它没有跟着'晚上'和比赛"今天[blah blah]星期一晚上,但[等等]星期一"。
答案 0 :(得分:1)
你可能想要这样的东西......
def search2lookahead(rex, txt, tag):
m= re.search(rex,txt)
if m !=None:
if txt[m.end():].startswith(tag): return None
else: return m.group()
else: return None
rex = r'today.*?monday '
txt = 'today [blah blah] monday night but [blah blah] monday morning'
m = search2lookahead(rex,txt,"night")
print(m)