[英]Regexp to catch multiple latex command in a single line
我正在編寫一個乳膠到文本轉換器,並且將我的工作基於一個著名的乳膠Python解析器(python-latex)。 我每天都在改進它,但是現在在一行中解析多個命令時遇到了問題。 乳膠命令可以采用以下四種形式:
\commandname
\commandname[text]
\commandname{other text}
\commandname[text]{other text}
假設命令沒有分成幾行,並且文本中可能有空格(但命令名中沒有空格),我最后得到了以下正則表達式來捕獲一行命令:
'(\\.+\[*.*\]*\{.*\})'
實際上,一個示例程序正在運行:
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}']
我嘗試使用先行和回溯命題,但是由於它們期望使用固定數量的字符,因此無法使用它們。 我希望有一個解決方案。
謝謝!
您可以使用github.com/alvinwan/TexSoup輕松完成此操作 。 這將為您提供所需的內容,盡管保留了空格。
>>> 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要求使用正則表達式,但是假設該任務與工具無關,則將其留給有類似問題的人員使用。 另外,我寫了TexSoup,所以建議不要加鹽。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.