Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the regular expression returning an error in python?

Tags:

python

regex

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'

like image 550
Gath Avatar asked Sep 14 '26 10:09

Gath


2 Answers

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.

like image 136
kgiannakakis Avatar answered Sep 15 '26 23:09

kgiannakakis


Two issues:

  1. your pattern does not match, therefore m is set to None, and None has no group attribute.

  2. 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.)

like image 37
tzot Avatar answered Sep 16 '26 01:09

tzot



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!