用于匹配结束括号的正则表达式

时间:2017-05-17 07:03:24

标签: python regex 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 regexp失败。如果我删除了ungreedy符号,那么它将匹配更多的文本,因为它全部在一行中,我想要从原始花括号匹配到关闭它的那个。

这样做的最佳方法是什么?由于摘要可以跨越几行,而标题通常是一行,我不确定这样做的最佳方法是什么。

我搜索过这个但找不到合适的解决方案。

谢谢!

1 个答案:

答案 0 :(得分:3)

如果胡须的嵌套只有1级,那么这个正则表达式应该接近你想要的。

\\(My\w+)[{]((?:[^{}]*|[{][^{}]*[}])*)[}]

您可以对其进行测试here

如果这不是Python re模块,而是支持递归的正则表达式引擎 (比如PCRE或PyPi regex),那么这样的正则表达式可以起作用:

[\\](My\w+)([{](?>[^{}]+|(?2))*[}])
相关问题