什么是sre_constants.error:没有什么可重复的

时间:2012-09-12 14:16:50

标签: python regex

我遇到了一个看似简单的Python正则表达式的问题。

# e.g. If I wanted to find "mark has wonderful kittens, but they're mischievous.."
p = re.compile("*kittens*")

这将失败并显示错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/re.py", line 190, in compile
    return _compile(pattern, flags)
  File "/usr/lib64/python2.7/re.py", line 242, in _compile
    raise error, v # invalid expression
sre_constants.error: nothing to repeat

我可能错过了一些非常简单的东西,正则表达肯定不是我的优势!

4 个答案:

答案 0 :(得分:20)

您将正则表达式与globs混淆。

你的意思是:

p = re.compile(".*kittens.*")

请注意,裸星号在RE中的含义与在glob表达式中的含义相同。

答案 1 :(得分:3)

*是一个元字符,意思是“0或更多前面的标记”,并且第一个*没有任何重复。

也许你正在寻找单词边界:

p = re.compile(r"\bkittens\b")

\b确保只匹配整个单词(因此这个正则表达式会失败,哼,"kittenshit"

答案 2 :(得分:0)

Q值。什么是re.py,sre.py,sre_constants.py?

答。 https://blog.labix.org/2003/06/16/understanding-pythons-sre-structure

代码:

our_regex = '.*pattern.*('
try:
 re.compile(our_regex)
except Exception, e:
 print e, type(e)

unbalanced parenthesis <class 'sre_constants.error'>

答案 3 :(得分:0)

这似乎是re模块抛出的错误。

要处理它,请导入sre_constants模块

这是一个小例子-使用Pandas数据框(这是我在查看时遇到的问题)。

import re
import sre_constants

try:
    df=d[d.Ex_Feed.str.contains('*123', regex=True)]
except sre_constants.error as err:
    print("SRE Error")
except Exception as error:
    print("Some other err Err")
    print("{}".format(type(err)))
    junk=1
finally:
    print("It's time for bed said Zeberdee")

希望有帮助