Python Forum
AttributeError: 'NoneType' object has no attribute 'group' - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: AttributeError: 'NoneType' object has no attribute 'group' (/thread-35948.html)



AttributeError: 'NoneType' object has no attribute 'group' - MaartenRo - Jan-02-2022

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'



RE: AttributeError: 'NoneType' object has no attribute 'group' - buran - Jan-02-2022

Here you can try/test your regex patterns
https://regex101.com/


RE: AttributeError: 'NoneType' object has no attribute 'group' - MaartenRo - Jan-02-2022

Thank you, that site for Regex testing is very useful.


RE: AttributeError: 'NoneType' object has no attribute 'group' - snippsat - Jan-02-2022

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