【问题标题】:sre_constants.error: nothing to repeatsre_constants.error:无需重复
【发布时间】:2015-03-15 02:10:21
【问题描述】:

我正在使用正则表达式,但出现错误:

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 以查看特别是哪一行出现问题时,它看起来像一条正常的行...

【问题讨论】:

  • 您的意见是什么?可变词的内容是什么?
  • print "SEARCHING",repr(string1),"for",word,otherWord 返回SEARCHING u'chapter 8 chromosome function cell cycle dynamic ' for dynamic +end
  • 你试过re.escape(word) 吗?
  • 嗯,肯定和+end有关
  • 谢谢,它似乎有效。只是为了仔细检查:我已经输入了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:,这是你的意思吗?

标签: python regex


【解决方案1】:

我建议您使用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:

【讨论】:

    猜你喜欢
    • 2018-05-21
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多