我有一个 latex 文件,里面可能有这种代码
\MyTitle{This is a title with some \commands{with some arguments} inside}
which is followed by some text
with many lines and any kind of things inside
and at some point an abstract can be defined like
\MyAbstract{%
including the abstract which can have also \commands{inside with possiblguments} or not and can longer than a line
我想做的是编写一些 python 代码,在文件中找到标题和摘要。我所做的和正在做的是将文件作为字符串读取并使用以下代码作为标题
abstract = re.search("\\\MyAbstract{(.*?)}", alltext).groups()[0]
title = re.search(r"\\MyTitle{(.*?)}", alltext).groups()[0]
在我找到一个标题或带有其他花括号的摘要之前,这一直很好用,这使得非贪婪的正则表达式失败了。如果我删除 ungreedy 符号,那么它将匹配更多的文本,因为它都在一行中,我想从原始花括号匹配到关闭它的那个。
这样做的最佳方法是什么?由于摘要可以跨越多行,而标题通常只有一行,所以我不确定这样做的最佳方式是什么。
我搜索过这个但找不到有效的解决方案。
谢谢!
请您参考如下方法:
如果 mustache 的嵌套只有一层,那么这个正则表达式应该接近你想要的。
\\(My\w+)[{]((?:[^{}]*|[{][^{}]*[}])*)[}]
可以测试一下here
如果这不是 Python 的 re 模块,而是一个支持递归的正则表达式引擎的话
(如 PCRE 或 PyPi regex ),那么像这样的正则表达式可以工作:
[\\](My\w+)([{](?>[^{}]+|(?2))*[}])
