Python Regexp在一行中捕获多个latex命令

Python Regexp在一行中捕获多个latex命令,python,regex,Python,Regex,我正在编写一个latex到文本的转换器,我的工作基于一个著名的Python latex解析器(Python latex)。我日复一日地改进它,但现在我在一行中解析多个命令时遇到了问题。latex命令可以采用以下四种形式: \commandname \commandname[text] \commandname{other text} \commandname[text]{other text} 假设命令未拆分为多行,并且文本中可能有空格(但命令名中没有空格),我使用以下regexp在一行中捕获

我正在编写一个latex到文本的转换器,我的工作基于一个著名的Python latex解析器(Python latex)。我日复一日地改进它,但现在我在一行中解析多个命令时遇到了问题。latex命令可以采用以下四种形式:

\commandname
\commandname[text]
\commandname{other text}
\commandname[text]{other text}
假设命令未拆分为多行,并且文本中可能有空格(但命令名中没有空格),我使用以下regexp在一行中捕获命令:

'(\\.+\[*.*\]*\{.*\})'
事实上,一个示例程序正在运行:

string="\documentclass[this is an option]{this is a text} this is other text ..."
re.split(r'(\\.+\[*.*\]*\{.*\}|\w+)+?', string)

>>>['', '\\documentclass[this is an option]{this is a text}', ' ', 'this', ' ', 'is', ' ', 'other', ' ', 'text', ' ...']
老实说,我更喜欢这样的输出:

>>> [ '\\documentclass[this is an option]{this is a text}', 'this is other text ...' ]
但第一种方法无论如何都能奏效。现在,如果一行中有多个命令,我的问题就会出现,如以下示例所示:

dstring=string+" \emph{tt}"
print (dstring)
\documentclass[this is an option]{this is a text} this is other text ... \emph{tt}
re.split(r'(\\.+\[*.*\]*\{.*\}|\w+)+?', dstring)
['', '\\documentclass[this is an option]{this is a text} this is other text ... \\emph{tt}', '']
如你所见,结果与我想要的结果大不相同:

[ '\\documentclass[this is an option]{this is a text}', 'this is other text ...', '\\emph{tt}']
我曾尝试使用“向前看”和“向后看”命题,但由于它们需要固定数量的字符,所以不可能使用它们。我希望有一个解决办法


谢谢大家!

您只需简单地使用。这将提供您想要的,尽管保留了空格

>>> from TexSoup import TexSoup
>>> string = "\documentclass[this is an option]{this is a text} this is other text ..."
>>> soup = TexSoup(string)
>>> list(soup.contents)
[\documentclass[this is an option]{this is a text}, ' this is other text ...']
>>> string2 = string + "\emph{tt}"
>>> soup2 = TexSoup(string2)
[\documentclass[this is an option]{this is a text}, ' this is other text ...', \emph{tt}]

免责声明:我知道(1)我在一年后发布了(2)OP要求使用regex,但假设任务与工具无关,我将把它留给有类似问题的人。此外,我还编写了TexSoup,因此请对此建议持保留态度。

Latex命令可以嵌套(从堆栈交换)。因此,如果可以嵌套,则可以使用支持递归的PyPi正则表达式模块对其进行解析。但在某种程度上。常规解析器将更加高效和安全。