Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sre_constants.error: nothing to repeat

Tags:

python

regex

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

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...

like image 439
user0 Avatar asked Jul 30 '26 08:07

user0


1 Answers

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:
like image 80
Avinash Raj Avatar answered Aug 01 '26 21:08

Avinash Raj