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


Step 2: Create a Regex for Email Addresses



Yüklə 397,03 Kb.
Pdf görüntüsü
səhifə21/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

Step 2: Create a Regex for Email Addresses
You will also need a regular expression that can match email addresses. 
Make your program look like the following:
#! python3
# phoneAndEmail.py - Finds phone numbers and email addresses on the clipboard.
import pyperclip, re
phoneRegex = re.compile(r'''(
--snip--
# Create email regex.
emailRegex = re.compile(r'''(
 [a-zA-Z0-9._%+-]+ # username
 @ # @ symbol
 [a-zA-Z0-9.-]+ # domain name
(\.[a-zA-Z]{2,4}) # dot-something
)''', re.VERBOSE)
# TODO: Find matches in clipboard text.
# TODO: Copy results to the clipboard.
The username part of the email address  is one or more characters 
that can be any of the following: lowercase and uppercase letters, numbers, 
a dot, an underscore, a percent sign, a plus sign, or a hyphen. You can put 
all of these into a character class: 
[a-zA-Z0-9._%+-]
.
The domain and username are separated by an @ symbol . The 
domain name  has a slightly less permissive character class with only 
letters, numbers, periods, and hyphens: 
[a-zA-Z0-9.-]
. And last will be 


182
Chapter 7
the “dot-com” part (technically known as the top-level domain), which can 
really be dot-anything. This is between two and four characters.
The format for email addresses has a lot of weird rules. This regular 
expression won’t match every possible valid email address, but it’ll match 
almost any typical email address you’ll encounter. 
Step 3: Find All Matches in the Clipboard Text
Now that you have specified the regular expressions for phone numbers 
and email addresses, you can let Python’s 
re
module do the hard work of 
finding all the matches on the clipboard. The 
pyperclip.paste()
function 
will get a string value of the text on the clipboard, and the 
findall()
regex 
method will return a list of tuples.
Make your program look like the following:
#! python3
# phoneAndEmail.py - Finds phone numbers and email addresses on the clipboard.
import pyperclip, re
phoneRegex = re.compile(r'''(
--snip--

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