I want to use a python regexp to remove the comments in a LaTeX file. In LaTeX a comment starts by "%". But if the % character is escaped ("\%") then its not a comment, its the symbol percent.
This task is just one among many regexp that I apply on my LaTeX text. I store all these reg exp in a list of dicts.
The problem I face is that the regexp I use for pruning the comments does not work (because I do not know how to specify the character set 'not backslash'). The backslash in the character set escapes the closing ']' and the regexp is incorrect.
My code:
regexps=[]
regexps.append({r'left':'%.*', 'right':r''}) # this strips all the comments, but messes up with the percent characters (\%)
regexps.append({r'left':'[^\]%.*', 'right':r''}) # this is incorrect (escapes the closing "]" )
return applyRegexps(latexText, regexps)
def applyRegexps(text, listRegExp):
""" Applies successively many regexps to a text"""
if testMode:
print str(listRegExp)
# apply all the regexps in the list
for element in listRegExp:
left = element['left']
right = element['right']
r=re.compile(left)
text=r.sub(right,text)
return text
Any help will be much appreciated. Thanks!
Gilles
Simply double the backslash, but do use a raw string literal to avoid having to double them again:
regexps.append({'left':r'[^\\]%.*', 'right':r''})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With