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 1: Create a Regex for Phone Numbers



Yüklə 397,03 Kb.
Pdf görüntüsü
səhifə20/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 1: Create a Regex for Phone Numbers
First, you have to create a regular expression to search for phone numbers. 
Create a new file, enter the following, and save it as phoneAndEmail.py:
#! python3
# phoneAndEmail.py - Finds phone numbers and email addresses on the clipboard.
import pyperclip, re
phoneRegex = 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)
# TODO: Create email regex.
# TODO: Find matches in clipboard text.
# TODO: Copy results to the clipboard.


Pattern Matching with Regular Expressions
181
The 
TODO
comments are just a skeleton for the program. They’ll be 
replaced as you write the actual code.
The phone number begins with an optional area code, so the area code 
group is followed with a question mark. Since the area code can be just three 
digits (that is, 
\d{3}
or three digits within parentheses (that is, 
\(\d{3}\)
), 
you should have a pipe joining those parts. You can add the regex comment 
# Area code
to this part of the multiline string to help you remember what 
(\d{3}|\(\d{3}\))?
is supposed to match.
The phone number separator character can be a space (
\s
), hyphen (
-
), 
or period (
.
), so these parts should also be joined by pipes. The next few 
parts of the regular expression are straightforward: three digits, followed 
by another separator, followed by four digits. The last part is an optional 
extension made up of any number of spaces followed by 
ext

x
, or 
ext.
, fol-
lowed by two to five digits. 
N O T E
 
It’s easy to get mixed up with regular expressions that contain groups with parenthe-
ses 
( ) 
and escaped parentheses 
\( \)
. Remember to double-check that you’re using 
the correct one if you get a “missing ), unterminated subpattern” error message. 

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