Skip to main content
 首页 » 编程设计

python之用于捕获科学引文的正则表达式

2024年09月03日33xxx_UU

我正在 try catch 其中至少有一位数字的文本括号(想想引文)。这是我的正则表达式,它工作正常: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) 

知道我做错了什么吗?

请您参考如下方法:

你可以使用

re.findall(r'\([^()\d]*\d[^()]*\)', s) 

参见 regex demo

详情

  • \( - 一个 ( 字符
  • [^()\d]* - 除了 (, ) 和数字
  • 之外的 0 个或更多字符
  • \d - 一个数字
  • [^()]* - 除了 (, )
  • 之外的 0 个或更多字符
  • \) - ) 字符。

参见 regex graph :

Python demo :

import re 
rx = re.compile(r"\([^()\d]*\d[^()]*\)") 
s = "Some (Author) and (Author 2000)" 
print(rx.findall(s)) # => ['(Author 2000)'] 

要获得不带括号的结果,请添加一个捕获组:

rx = re.compile(r"\(([^()\d]*\d[^()]*)\)") 
                    ^                ^ 

参见 this Python demo .