Python Forum

Full Version: AttributeError: 'NoneType' object has no attribute 'group'
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I would like my code to return '(415)'. What am i doing wrong?

phoneNumRegex=re.compile(r'(\(\d\d\d\))(\d\d\d-\d\d\d\d)')
mo=phoneNumRegex.search('My phonenumber is (415) 555-4242.')
mo.group(1)
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    mo.group(1)
AttributeError: 'NoneType' object has no attribute 'group'
Here you can try/test your regex patterns
https://regex101.com/
Thank you, that site for Regex testing is very useful.
Can also match previous integer,then don't have to type \d for every one.
So if group number in eg two groups.
import re

phoneNumRegex = re.compile(r'(\(\d{3}\))\s(\d.*)\.')
mo = phoneNumRegex.search('My phonenumber is (415) 555-4242.')
>>> mo.group(1)
'(415)'
>>> mo.group(2)
'555-4242'
>>> mo.groups()
('(415)', '555-4242')