在python中使用regex从tex文件中提取引用的bibtex密钥

2024-10-01 15:31:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python中的regex从一个LaTeX文档中提取引用的BibTeX键。你知道吗

我想排除引用,如果它被注释掉(%)在前面,但仍然包括它,如果有百分号(\%)在前面。你知道吗

以下是我到目前为止得出的结论:

\\(?:no|)cite\w*\{(.*?)\}

举个例子:

blablabla
Author et. al \cite{author92} bla bla. % should match
\citep{author93} % should match
\nocite{author94} % should match
100\%\nocite{author95} % should match
100\% \nocite{author95} % should match
%\nocite{author96} % should not match
\cite{author97, author98, author99} % should match
\nocite{*} % should not match

Regex101测试:https://regex101.com/r/ZaI8kG/2/

谢谢你的帮助。你知道吗


Tags: no文档matchnotbibtex例子regexlatex
2条回答

将较新的regex模块(pip install regex)与以下表达式一起使用:

(?<!\\)%.+(*SKIP)(*FAIL)|\\(?:no)?citep?\{(?P<author>(?!\*)[^{}]+)\}

a demo on regex101.com


更详细:
(?<!\\)%.+(*SKIP)(*FAIL)     # % (not preceded by \) 
                             # and the whole line shall fail
|                            # or
\\(?:no)?citep?              # \nocite, \cite or \citep
\{                           # { literally
    (?P<author>(?!\*)[^{}]+) # must not start with a star
\}                           # } literally


如果不能选择安装另一个库,则需要将表达式更改为
(?<!\\)%.+
|
(\\(?:no)?citep?
\{
    ((?!\*)[^{}]+)
\})

并且需要通过编程检查是否设置了第二个捕获组(即不为空)。
后者可能位于Python

import re

latex = r"""
blablabla
Author et. al \cite{author92} bla bla. % should match
\citep{author93} % should match
\nocite{author94} % should match
100\%\nocite{author95} % should match
100\% \nocite{author95} % should match
%\nocite{author96} % should not match
\cite{author97, author98, author99} % should match
\nocite{*} % should not match
"""

rx = re.compile(r'''(?<!\\)%.+|(\\(?:no)?citep?\{((?!\*)[^{}]+)\})''')

authors = [m.group(2) for m in rx.finditer(latex) if m.group(2)]
print(authors)

这就产生了

['author92', 'author93', 'author94', 'author95', 'author95', 'author97, author98, author99']

我没有遵循最后一个的逻辑,在我看来*可能不是{}所需要的,在这种情况下,也许您希望设计一个类似于以下内容的表达式:

^(?!(%\\(?:no)?cite\w*\{([^}]*?)\}))[^*\n]*$

但不确定。你知道吗

DEMO

相关问题 更多 >

    热门问题