我试图抓住括号内至少有一个数字的文本(想想引文)。这是我现在的正则表达式,它工作正常:https://regex101.com/r/oOHPvO/5
\((?=.*\d).+?\)
所以我想让它捕捉(Author 2000)
和(2000)
,而不是(Author)
。你知道吗
我试图使用python捕获所有这些括号,但是在python中,它也捕获括号中的文本,即使它们没有数字。你知道吗
import re
with open('text.txt') as f:
f = f.read()
s = "\((?=.*\d).*?\)"
citations = re.findall(s, f)
citations = list(set(citations))
for c in citations:
print (c)
你知道我做错了什么吗?你知道吗
你可以用
参见regex demo
细节
\(
-a(
字符[^()\d]*
-0个或更多字符,而不是(
、)
和数字\d
-一个数字[^()]*
-0个或更多字符,而不是(
,)
\)
-a)
字符。你知道吗参见regex graph:
Python demo:
要获得不带括号的结果,请添加捕获组:
见this Python demo。你知道吗
处理此表达式最可靠的方法可能是在表达式可能增长时添加边界。例如,我们可以尝试创建char列表,从中收集所需的数据:
DEMO
测试
演示
正则表达式电路
jex.im可视化正则表达式:
相关问题 更多 >
编程相关推荐