问题描述
我在使用这个表达式时收到一条错误消息:
re.sub(r"([^\s\w])(\s*\1)+","\\1","...")
我在 RegExr 检查了正则表达式,它按预期返回 .
.但是当我在 Python 中尝试时,我收到此错误消息:
raise error, v # 无效表达式sre_constants.error: 没有什么可重复的
谁能解释一下?
这似乎是一个 python 错误(在 vim 中完美运行).问题的根源是 (\s*...)+ 位.基本上,你不能做有意义的 (\s*)+
,因为你试图重复一些可能为空的东西.
然而 (\s*\1)
不应该为空,但我们知道它只是因为我们知道 \1 中的内容.显然 python 不会......这很奇怪.
I get an error message when I use this expression:
re.sub(r"([^\s\w])(\s*\1)+","\\1","...")
I checked the regex at RegExr and it returns .
as expected. But when I try it in Python I get this error message:
raise error, v # invalid expression
sre_constants.error: nothing to repeat
Can someone please explain?
It seems to be a python bug (that works perfectly in vim).The source of the problem is the (\s*...)+ bit. Basically , you can't do (\s*)+
which make sense , because you are trying to repeat something which can be null.
>>> 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
However (\s*\1)
should not be null, but we know it only because we know what's in \1. Apparently python doesn't ... that's weird.
这篇关于正则表达式错误 - 无需重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!