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
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With