使用此表达式时出现错误消息:
re.sub(r"([^\s\w])(\s*\1)+","\\1","...")
我在RegExr中检查了正则表达式,它.
按预期返回。但是当我在Python中尝试时,出现以下错误消息:
raise error, v # invalid expression
sre_constants.error: nothing to repeat
有人可以解释一下吗?
使用此表达式时出现错误消息:
re.sub(r"([^\s\w])(\s*\1)+","\\1","...")
我在RegExr中检查了正则表达式,它.
按预期返回。但是当我在Python中尝试时,出现以下错误消息:
raise error, v # invalid expression
sre_constants.error: nothing to repeat
有人可以解释一下吗?
Answers:
这似乎是一个python错误(在vim中完美运行)。问题的根源是(\ s * ...)+位。基本上,您无法做到(\s*)+
这一点,因为您正在尝试重复可能为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
但是(\s*\1)
不应该为null,而是仅因为我们知道\ 1中的内容而知道它。显然python并不...这很奇怪。
实际上,这不仅是带有*的Python错误,而且在将字符串作为要编译的正则表达式的一部分传递时也可能发生,例如;
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)
如果处理过的行包含一些“(+)”(例如,您可以在化学式中找到)或此类字符链,则将导致错误。解决方案是逃脱,但是当您即时进行操作时,可能会发生无法正确执行操作的情况...
正则表达式通常在语言理论中使用*和+。执行行代码时遇到相同的错误
re.split("*",text)
要解决它,它需要在*和+之前包含\
re.split("\*",text)