python - 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]]'>
似乎消极的后视不起作用。我究竟做错了什么?谢谢!
解决方案
您可以改为使用负前瞻检查。还要检查使用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]]'>
推荐阅读
- printf - 来自控制台的 scanf 和来自文件的 fscanf
- python-3.x - 如何使用 python-telegram-bot 仅回答最新的用户内联查询?
- postgresql - PostgreSQL 用户密码从 MD5 更改为 scram-sha-265
- python - 限制命令行中输入数量的替代方法
- python-3.x - 如何使用 python 目录中不同文件夹中的文本文件制作单列数据框?
- php - 419 抱歉,您的会话已过期。请刷新并重试
- javascript - jQuery 中是否有任何可用于可拖动包含的替代 javascript 函数?
- gnuplot - Key 中轮廓级别的标签
- xml - 无法使用 perl 从 XML 文件中获取值
- r - 通过函数式编程消除for循环