4

I am using Python's regex with an if-statement: if the match is None, then it should go to the else clause. But it shows this error:

AttributeError: 'NoneType' object has no attribute 'group'

The script is:

import string
chars = re.escape(string.punctuation)
sub='FW: Re: 29699' 
if re.search("^FW: (\w{10})",sub).group(1) is not None :
    d=re.search("^FW: (\w{10})",sub).group(1)
else:
    a=re.sub(r'['+chars+']', ' ',sub)
    d='_'.join(a.split())

Every help is great help!

4
  • 1
    You've written is not None rather than is None, which seems to be what you need. Commented May 22, 2017 at 5:00
  • First error is import re Commented May 22, 2017 at 5:00
  • Even then it's not working Commented May 22, 2017 at 5:00
  • You cannot group none objects Commented May 22, 2017 at 5:05

1 Answer 1

6

Your problem is this: if your search doesn't find anything, it will return None. You can't do None.group(1), which is what your code amounts to. Instead, check whether the search result is None—not the search result's first group.

import re
import string

chars = re.escape(string.punctuation)
sub='FW: Re: 29699' 
search_result = re.search(r"^FW: (\w{10})", sub)

if search_result is not None:
    d = search_result.group(1)
else:
    a = re.sub(r'['+chars+']', ' ', sub)
    d = '_'.join(a.split())

print(d)
# FW_RE_29699
Sign up to request clarification or add additional context in comments.

1 Comment

that's so logical, Thanks!

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.