【问题标题】:Python regex negative lookbehind issue [duplicate]Python 正则表达式负后向问题[重复]
【发布时间】:2020-06-26 10:37:37
【问题描述】:

我想使用 python re 包搜索以“[[”开头的字符串,即 not 后跟“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]]'>

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

【问题讨论】:

标签: python regex


【解决方案1】:

您可以改为使用否定前瞻检查。还可以使用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]]'>

【讨论】:

  • 太好了,它有效。谢谢!
  • 如果要搜索多行文本,也可以使用 re.findall 或 re.finditer 方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-15
  • 1970-01-01
  • 1970-01-01
  • 2016-01-31
  • 1970-01-01
  • 2018-04-03
  • 1970-01-01
相关资源
最近更新 更多