Jeremyapple
Jeremyapple

Reputation: 263

invalid expression sre_constants.error: nothing to repeat

I am trying to match the data in output variable ,am looking to match the word after *,am trying the following way but running into an error, how to 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

Upvotes: 3

Views: 848

Answers (1)

cs95
cs95

Reputation: 403012

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

Another suggestion would be to use a lookbehind, so you don't need to use another capture group:

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

Upvotes: 3

Related Questions