3

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'

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It's actually m that is None. (Minor nit.)
5

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

Comments

2

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.

Comments

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

Comments

1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.