Gath
Gath

Reputation: 559

Why is the regular expression returning an error in python?

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'

Upvotes: 3

Views: 12424

Answers (5)

tzot
tzot

Reputation: 95951

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

Upvotes: 5

Eugene Morozov
Eugene Morozov

Reputation: 15816

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'

Upvotes: 1

kgiannakakis
kgiannakakis

Reputation: 104178

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.

Upvotes: 5

Andrea Ambu
Andrea Ambu

Reputation: 39516

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

Upvotes: 2

SilentGhost
SilentGhost

Reputation: 319611

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.

Upvotes: 2

Related Questions