Python Forum
Coding understanding help - 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: Coding understanding help (/thread-19885.html)



Coding understanding help - srikanth - Jul-18-2019

Hello Hi, I am new to python and i am learning from automating the boring stuff.
In this program, why and how did he choose groups[1],groups[3],groups[5] and groups[8]. can you please explain the program briefly, especially the for loop part for finding mobile numbers.
import re, pyperclip
phonenumber= re.compile(r'''(
    (\d{3}|\(\d{3}\))?            # area code
    (\s|-|\.)?                    # separator
    \d{3}                         # first 3 digits
    (\s|-|\.)                     # separator
    \d{4}                         # last 4 digits
    (\s*(ext|x|ext.)\s*\d{2,5})?  # extension
    )''', re.VERBOSE)

emailids=re.compile(r'''(
       [a-zA-Z0-9-.%+]+     #username
       @                    #@
       [a-zA-Z0-9.-]+
         (\.[a-zA-Z]{2,4}))''',re.VERBOSE)

text=str(pyperclip.paste())
matches=[]
for groups in phonenumber.findall(text):
    phonenum = '-'.join([groups[1],groups[3],groups[5]])
    print(groups)
    if groups[8]!='':
        phonenum +=' x'+groups[8]
    matches.append(phonenum)

for groups in emailids.findall(text):
    matches.append(groups[0])

if len(matches)>0:
    pyperclip.copy('\n'.join(matches))
    print('copied to clipboard')
    print('\n'.join(matches))
else:
    print('no phone number and email ids are found')
Thanks in Advance


RE: Coding understanding help - Larz60+ - Jul-19-2019

I believe that this line:
text=str(pyperclip.paste())
copies the clipboard text into variable text.
Then groups is what is found using phonenumber regex
groups[1], groups[2], groups[5] are the 2nd, 3rd and 6th positions in the result of regex find (zero based)