Python – Invalid expression sre_constants.error : nothing to repeat

Invalid expression sre_constants.error : nothing to repeat… here is a solution to the problem.

Invalid expression sre_constants.error : nothing to repeat

I’m trying to match data in an output variable, I’m looking for words after matching *, I’m trying the following but getting an error, how do I fix it?

import re
output = """test
          * Peace
            master"""
m = re.search('* (\w+)', output)
print m.group(0)

Error: –

Traceback (most recent call last):
  File "testinglogic.py", line 7, in <module>
    m = re.search('* (\w+)', output)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 146, in search
    return _compile(pattern, flags).search(string)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 251, in _compile
    raise error, v # invalid expression
sre_constants.error: nothing to repeat

Solution

The first fix is to escape the *, because you want the engine to treat it literally (as an asterisk), so you escape it with a backslash.

Another suggestion is to use lookbehind, so you don’t need to use another capture group:

>>> re.search('(?<=\*\s)\w+', output).group()
'Peace'

Related Problems and Solutions