正则表达式错误 - 无需重复 [英] regex error - nothing to repeat

查看:54
本文介绍了正则表达式错误 - 无需重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用这个表达式时收到一条错误消息:

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

我在 RegExr 检查了正则表达式,它按预期返回 ..但是当我在 Python 中尝试时,我收到此错误消息:

raise error, v # 无效表达式sre_constants.error: 没有什么可重复的

谁能解释一下?

解决方案

这似乎是一个 python 错误(在 vim 中完美运行).问题的根源是 (\s*...)+ 位.基本上,你不能做有意义的 (\s*)+ ,因为你试图重复一些可能为空的东西.

<预><代码>>>>re.compile(r"(\s*)+")回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py",第180行,编译返回_compile(模式,标志)文件/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/re.py",第 233 行,在 _compile引发错误,v # 无效的表达式sre_constants.error: 没有什么可重复的

然而 (\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.

这篇关于正则表达式错误 - 无需重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆