Am trying the following regular expression in python but it returns an error
import re
...
#read a line from a file to variable line
# loking for the pattern 'WORD' in the line ...
m=re.search('(?<=[WORD])\w+',str(line))
m.group(0)
i get the following error:
AttributeError: 'NoneType' object has no attribute 'group'
This is happening because the regular expression wasn't matched. Therefore m is None and of course you can't access group[0]. You need to first test that the search was successful, before trying to access group members.
Two issues:
your pattern does not match, therefore m is set to None, and None has no group attribute.
I believe you meant either:
m= re.search(r"(?<=WORD)\w+", str(line))
as entered, or
m= re.search(r"(?P<WORD>\w+)", str(line))
The former matches "abc" in "WORDabc def"; the latter matches "abc" in "abc def" and the match object will have a .group("WORD") containing "abc". (Using r"" strings is generally a good idea when specifying regular expressions.)
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