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

时间:2015-03-15 02:10:22

标签: python regex

我正在使用正则表达式,我收到错误:

Traceback (most recent call last):
  File "tokennet.py", line 825, in <module>
    RunIt(ContentToRun,Content[0])
  File "tokennet.py", line 401, in RunIt
     if re.search(r'\b'+word+r'\b', str1) and re.search(r'\b'+otherWord+r'\b',   str1) and word != otherWord:
   File     "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py",     line 142, in search
     return _compile(pattern, flags).search(string)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 242, in _compile
raise error, v # invalid expression
sre_constants.error: nothing to repeat

我环顾四周,似乎这个错误与*有关,但不确定我为什么会这样做。我必须做些什么才能str1停止获取它? str1是一个大型文本文件中的一行,当我打印str1以查看特别是哪条线路时,它看起来像一条正常的线......

1 个答案:

答案 0 :(得分:5)

我建议您使用re.escape(word),因为您的变量word可能包含任何正则表达式特殊字符。我认为错误是因为变量中存在特殊字符。通过使用re.escape(variable-name),它可以转义变量中存在的任何特殊字符。

if re.search(r'\b'+re.escape(word)+r'\b', str1) and re.search(r'\b'+re.escape(otherWord)+r'\b', str1) and word != otherWord: