regex python捕获大括号内的选择性内容,包括大括号子级别和n字符



regex python catchselective花括号内的内容,包括花括号子级别

最好的解释是一个最小的代表性示例(正如您所看到的,对于那些知道latex..的人来说,.bib ..)。下面是代表性的原始输入文本:

text = """
@book{book1,
title={tit1},
author={aut1}
}
@article{art2,
title={tit2},
author={aut2}
}
@article{art3,
title={tit3},
author={aut3}
}
"""

和这里是我的尝试(我失败了…)提取的内容内花括号仅为@article字段。请注意,其中有n个跳跃也想要收集。

regexpresion = r'@article{[.*n]+}'
result       = re.findall(regexpresion, text)

这就是我想要得到的,

>>> result
['art2,ntitle={tit2},nauthor={aut2}', 'art3,ntitle={tit3},nauthor={aut3}']

非常感谢你的经验

您可以使用两步方法,首先匹配以@article开头的部分,然后在第二步中删除您不希望在结果中出现的部分。

匹配所有部分的模式:

^@article{.*(?:n(?!@w+{).*)+(?=n}$)

  • ^字符串
  • 起始
  • @article{.*匹配@article{和其余行
  • (?:非捕获组
    • n(?!@w+{).*如果换行符不以@{
    • 开头,则匹配换行符和该行的其余部分
  • )+关闭非捕获组并重复它以匹配所有行
  • (?=n}$)正向向前看,在字符串
  • 的末尾断言一个换行符和}

查看regex101上的匹配

替换中的模式匹配@article{或(使用管道字符|) 1在换行符后的一个或多个空格。

@article{|(?<=n)[^Sn]+

例子
import re
pattern = r"^@article{.*(?:n(?!@w+{).*)+(?=n}$)"
s = ("@book{book1,n"
"  title={tit1},n"
"  author={aut1}n"
"}n"
"@article{art2,n"
"  title={tit2},n"
"  author={aut2}n"
"}n"
"@article{art3,n"
"  title={tit3},n"
"  author={aut3}n"
"}")
res = [re.sub(r"@article{|(?<=n)[^Sn]+", "", m) for m in re.findall(pattern, s, re.M)]
print(res)

输出
['art2,ntitle={tit2},nauthor={aut2}', 'art3,ntitle={tit3},nauthor={aut3}']

试试这个:

results = re.findall(r'{(.*?)}', text)

输出如下:

['tit1', 'aut1', 'tit2', 'aut2', 'tit3', 'aut3']

以下是我对regexpression的解决方案。它不是很优雅,很基本。

regexpression = r'@article{w+,ns+w+={.*?},ns+w+={.*?}'

regexpression的澄清分解:

r'@article{w+,n # catches the article field, 1st line
s+w+={.*?},n  # title sub-field, comma, new line,
s+w+={.*?}     # author sub-field

最新更新