【发布时间】:2012-11-13 17:00:29
【问题描述】:
我想使用 python 正则表达式来删除 LaTeX 文件中的 cmets。在 LaTeX 中,注释以“%”开头。但是如果 % 字符被转义(“\%”),那么它不是注释,它是符号百分比。
这项任务只是我在 LaTeX 文本中应用的众多正则表达式之一。我将所有这些 reg exp 存储在一个字典列表中。
我面临的问题是我用于修剪 cmets 的正则表达式不起作用(因为我不知道如何指定字符集“非反斜杠”)。字符集中的反斜杠转义结束的']',正则表达式不正确。
我的代码:
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
任何帮助将不胜感激。谢谢!
吉尔
【问题讨论】:
-
您是否尝试使用
r'[^\\]'? `\` 应该是用于转义反斜杠的正则表达式语法 -
如果你想在正则表达式中加入文字反斜杠,加倍。你的模式应该是 '[^\]%.*'
-
谢谢大家,Martijn Pieters 的回答很有效。我一定是累了……