Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Coding understanding help
#1
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
Reply
#2
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  New to python/coding Need help on Understanding why this code isn't working. Thanks! mat3372 8 1,740 May-09-2023, 08:47 AM
Last Post: buran
  coding understanding help kapman2006 5 5,274 Nov-06-2016, 09:52 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020