sre_constants.error: 没有什么可重复的 [英] sre_constants.error: nothing to repeat

查看:52
本文介绍了sre_constants.error: 没有什么可重复的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using a regex and I get the error:

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 以查看特别是哪一行被窃听时,它看起来像一条普通行...

I've looked around, and it seems this error is associated with *, but not sure why I'm getting it. What do I have to do to str1 to stop getting it? str1 is one line in a massive text file, and when I print str1 to see what line in particular is bugging, it looks like a normal line...

推荐答案

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

I suggest you to use re.escape(word), since your variable word may contain any regex special characters. I think the error came because of special characters present inside the variable. By using re.escape(variable-name), it escapes any special characters present inside the variable.

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:

这篇关于sre_constants.error: 没有什么可重复的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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