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

标签 python regex python-re

我正在 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 :

enter image description here

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 .

关于python - 用于捕获科学引文的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56317078/

相关文章:

python - 抓取 : How to fetch an attribute in a <abbr> tag

python - 将包含用于 Python 变量赋值的文本的字符串转换为实际变量

python - 使用 QObject 从 Python 线程发出信号

正则表达式仅替换 gedit 中的一部分

python - 如何计算 python 中两个向量数组的点积?

regex - 使用 bash 和/或 awk 在模式上分割字符串

c# - RichTextBox 中的代码折叠

python - 如何对 Python 字符串中的特殊字符进行转义?

python - 从数据框列的列表中查找字符串值并将字符串值附加为列

python - 正则表达式匹配尽可能少的字符