无效的表达式/缺少的组名

问题描述 投票:1回答:1

我正在使用python 2.7.17,正在尝试进行一些正则表达式操作。一切正常,直到遇到以下错误:

Traceback (most recent call last):
  File "latex/latex.py", line 130, in <module>
    contents = re.sub(re.escape(i),img,contents, 0, re.MULTILINE)
  File "/usr/lib/python2.7/re.py", line 155, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/usr/lib/python2.7/re.py", line 286, in _subx
    template = _compile_repl(template, pattern)
  File "/usr/lib/python2.7/re.py", line 273, in _compile_repl
    raise error, v # invalid expression
sre_constants.error: missing group name

我不知道出了什么问题,因为我实际上是在将字符串放入sub之前转义了该字符串:

print "----"                                                                   
print i                                                                        
print re.escape(i)                                                             
print img                                                                      
contents = re.sub(re.escape(i),img,contents, 0, re.MULTILINE)

这是打印语句产生的内容:

----
$$n \in \Z_{\geq 0}$$
\$\$n\ \\in\ \\Z\_\{\\geq\ 0\}\$\$
<img class="latex inline" src="{filename}/images/latex-cache/symmetric-functions.md827a2321d2328298b1d5789840928039.png" /><!--n \in \Z_{\geq 0}-->

如您所见,它正确地转义了字符串,但是由于某种原因,它引发了错误。我不知道这是什么错误,因为我可以找到的所有文章(例如regex error : raise error, v # invalid expression)都不能转义字符串。

任何帮助将不胜感激。

编辑

内容的内容是从文件中提取的。我编辑了脚本,还打印了内容。这是我的内容:

<div class="content">
Let $$n \in \Z_{\geq 0}$$
</div>

编辑2

看来错误来自img。当我用其他任何东西替换img时,它都可以正常工作。在以下情况下,我能够将其范围缩小到失败:

img = "\g"

我应该以某种方式逃避img吗?

我也尝试过:

img = "\\g"

并且这也导致了相同的错误。

python regex python-2.7 substitution
1个回答
0
投票

因此事实证明原因是\g在re.sub中是特殊的,并且用于找到的组(与\1\2等相同)。所以这是一个特殊字符。为了解决这个问题,您需要对其进行转义,但是由于python在转义方面很有趣,因此您需要对转义进行转义。换句话说,您想要:

contents = re.sub(re.escape(i),img.replace('\\','\\\\'),contents, 0, re.MULTILINE)

有关更详尽的解释,您可以在以下位置查看答案:Python Regex escape operator \ in substitutions & raw strings

© www.soinside.com 2019 - 2024. All rights reserved.