首页 > 解决方案 > Python 正则表达式负后视问题

问题描述

我想使用pythonre包搜索以“[[”开头的字符串,后面没有“Category:”,具有任意数量的字符并以“]]”结尾。我尝试了以下代码:

s="blah [[Category:Cartooning]] blah"
regex = re.compile(r"\[\[(?<!Category:).*?\]\]")
res = regex.search(s)
if res!=None:
    print(res)
else:
    print('no match')

并得到以下回复:

<re.Match object; span=(5, 28), match='[[Category:Cartooning]]'>

似乎消极的后视不起作用。我究竟做错了什么?谢谢!

标签: pythonregex

解决方案


您可以改为使用负前瞻检查。还要检查使用is not None. 还添加了通过和失败的文本:

import re

regex = re.compile(r"\[\[(?!Category:).*?\]\]")

s = "blah [[Category:Cartooning]] blah"
keep = "blah [[Cat:Cartooning]] blah"
texts = [s, keep]

results = [regex.search(i) for i in texts]
for res in results:
    if res is not None:
        print(res)
    else:
        print('no match')

回报:

no match
<re.Match object; span=(5, 23), match='[[Cat:Cartooning]]'>

推荐阅读