Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid expression sre_constants.error: nothing to repeat

Tags:

python

regex

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
like image 831
Jeremyapple Avatar asked Jan 31 '26 04:01

Jeremyapple


1 Answers

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'
like image 197
cs95 Avatar answered Feb 02 '26 17:02

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!