用于完成乳胶命令的正则表达式

Regexp for completing the latex command

好的,我想使用正则表达式来更改我的 .tex 文件。

我有下一个模式:'\mathcal{ <some letter>' 没有结束第二个大括号。我需要将它从右侧粘贴到 <some letter>。请注意,我在第一个大括号后有 white space

我已经完成了这个正则表达式:

import sys
import re

with open('output.tex', 'w') as out:
    with open('input.tex', 'r') as file:
        for line in file:
            newline = re.sub('mathcal{..?', 'mathcal{\1}', line)
            out.write(newline)

但它似乎不适用于错误“无效的组引用 1 在位置 9”。怎么弄好?

示例: 所以输入:Let $f$ --- choice function, given on $\mathcal{ B$。我希望它是:Let $f$ --- choice function, given on $\mathcal{ B}$

感谢您编辑您的问题。我不熟悉乳胶,但看起来你只想使用正则表达式在单个大写字符和 $ 之间插入 }。让我知道这个解决方案是否不够通用:

import re

line = "Let $f$ --- choice function, given on $\mathcal{ B$"

pattern = "mathcal{ ([A-Z])\$"

new_line = re.sub(pattern, "mathcal{ \1}$", line)
print(new_line)

输出:

Let $f$ --- choice function, given on $\mathcal{ B}$
>>>