【问题标题】:invalid expression/missing group name无效的表达式/缺少组名
【发布时间】:2020-07-02 09:04:33
【问题描述】:

我正在使用 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"

这也导致了同样的错误。

【问题讨论】:

  • 我相信您上面显示的i 的值不是实际导致错误的值。
  • contents 传入的变量 re.sub() 中有什么?
  • @s.dallapalma 我刚刚用“contents”的值编辑了我的帖子
  • 您希望在re.sub() 之后的内容中看到什么?
  • 它应该用 img 替换 i。

标签: python regex python-2.7 substitution


【解决方案1】:

所以原来是因为\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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    相关资源
    最近更新 更多