正则表达式错误-无需表示

2024-05-14 06:38:26 发布

您现在位置:Python中文网/ 问答频道 /正文

当我使用此表达式时,会收到错误消息:

re.sub(r"([^\s\w])(\s*\1)+","\\1","...")

我检查了位于RegExr的regex,它按预期返回.。但是当我在Python中尝试时,我得到了一条错误消息:

raise error, v # invalid expression
sre_constants.error: nothing to repeat

有人能解释一下吗?


Tags: tore消息表达式错误errorregexraise
3条回答

这是一个介于“*”和特殊字符之间的Python错误。

而不是

re.compile(r"\w*")

尝试:

re.compile(r"[a-zA-Z0-9]*")

但是,它不会生成相同的正则表达式。

此错误似乎已在2.7.5和2.7.6之间修复。

这不仅是Python的一个bug,*实际上,当您将字符串作为要编译的正则表达式的一部分传递时,也可能发生这种情况,例如

import re
input_line = "string from any input source"
processed_line= "text to be edited with {}".format(input_line)
target = "text to be searched"
re.search(processed_line, target)

如果处理过的行包含一些“(+)”,例如,您可以在化学公式或此类字符链中找到,则这将导致错误。 解决办法是逃避,但当你在飞行中,它可能会发生,你做不好。。。

它似乎是一个python bug(在vim中工作得很好)。 问题的根源是(\s*…)+位。基本上,你不能做有意义的(\s*)+,因为你试图重复一些可以为空的东西。

>>> re.compile(r"(\s*)+")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", line 180, in compile
    return _compile(pattern, flags)
  File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py", line 233, in _compile
    raise error, v # invalid expression
sre_constants.error: nothing to repeat

但是(\s*\1)不应该为空,但是我们知道它只是因为我们知道在1中有什么。显然Python不会。。。真奇怪。

相关问题 更多 >