Regexp for completing the latex command

Ok, I want to use regular expressions for changing my .tex file.

I have next patterns: 'mathcal{ <some letter>' without ending second brace. I need to glue it to <some letter> from the right side. Note that I have white space after first brace.

I’ve done this regexp:

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)

but it seems not to work with the error “invalid group reference 1 at position 9“. How to make it right?

Example: so to the input: Let $f$ --- choice function, given on $mathcal{ B$. I want it to be: Let $f$ --- choice function, given on $mathcal{ B}$

Answer

Thanks for editing your question. I’m not familiar with latex, but it seems like you just want to use a regex to insert a } between the single uppercase character and the $. Let me know if this solution isn’t general enough:

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)

Output:

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