7 pat t e r n m at c h I n g w I t h r e g u L a r e X p r e s s I o n s



Yüklə 397,03 Kb.
Pdf görüntüsü
səhifə22/25
tarix29.11.2022
ölçüsü397,03 Kb.
#71308
1   ...   17   18   19   20   21   22   23   24   25
P A T T E R N M A T C H I N G W I T H

# Find matches in clipboard text.
text = str(pyperclip.paste())

 matches = []

 for groups in phoneRegex.findall(text):
phoneNum = '-'.join([groups[1], groups[3], groups[5]])
if groups[8] != '':
phoneNum += ' x' + groups[8]
matches.append(phoneNum)

 for groups in emailRegex.findall(text):
matches.append(groups[0])
# TODO: Copy results to the clipboard.
There is one tuple for each match, and each tuple contains strings for 
each group in the regular expression. Remember that group 
0
matches the 
entire regular expression, so the group at index 
0
of the tuple is the one you 
are interested in.
As you can see at , you’ll store the matches in a list variable named 
matches
. It starts off as an empty list, and a couple 
for
loops. For the email 
addresses, you append group 
0
of each match . For the matched phone 
numbers, you don’t want to just append group 
0
. While the program detects 
phone numbers in several formats, you want the phone number appended 
to be in a single, standard format. The 
phoneNum
variable contains a string 
built from groups 
1

3

5
, and 
8
of the matched text . (These groups are 
the area code, first three digits, last four digits, and extension.)


Pattern Matching with Regular Expressions
183
Step 4: Join the Matches into a String for the Clipboard
Now that you have the email addresses and phone numbers as a list of strings 
in 
matches
, you want to put them on the clipboard. The 
pyperclip.copy()
func-
tion takes only a single string value, not a list of strings, so you call the 
join()
method on 
matches
.
To make it easier to see that the program is working, let’s print any 
matches you find to the terminal. If no phone numbers or email addresses 
were found, the program should tell the user this.
Make your program look like the following:
#! python3
# phoneAndEmail.py - Finds phone numbers and email addresses on the clipboard.
--snip--
for groups in emailRegex.findall(text):
matches.append(groups[0])

Yüklə 397,03 Kb.

Dostları ilə paylaş:
1   ...   17   18   19   20   21   22   23   24   25




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin