tags:

views:

170

answers:

5

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'

+2  A: 

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.

kgiannakakis
It's actually m that is None. (Minor nit.)
Lars Wirzenius
+1  A: 

re.search documentation says:

Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

SilentGhost
+1  A: 
>>> help(re.search)
Help on function search in module re:

search(pattern, string, flags=0)
    Scan through string looking for a match to the pattern, returning
    a match object, or None if no match was found.

Look at the last line: returning None if no match was found

Andrea Ambu
+1  A: 

BTW, your regular expression is incorrect. If you look for 'WORD', it should be just 'WORD'. str is also extraneous. Your code should look like this:

m = re.search('WORD', line)
if m:
    print m.group[0]

Your original regexp will return probably unexpected and undesired results:

>>> m = re.search('(?<=[WORD])\w+', 'WORDnet')
>>> m.group(0)
'ORDnet'
Eugene Morozov
+1  A: 

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

ΤΖΩΤΖΙΟΥ