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ə23/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

# Copy results to the clipboard.
if len(matches) > 0:
pyperclip.copy('\n'.join(matches))
print('Copied to clipboard:')
print('\n'.join(matches))
else:
print('No phone numbers or email addresses found.')
Running the Program
For an example, open your web browser to the No Starch Press contact page 
at https://nostarch.com/contactus/, press 
ctrl
-A to select all the text on the 
page, and press 
ctrl
-C to copy it to the clipboard. When you run this pro-
gram, the output will look something like this:
Copied to clipboard:
800-420-7240
415-863-9900
415-863-9950
info@nostarch.com
media@nostarch.com
academic@nostarch.com
info@nostarch.com
Ideas for Similar Programs
Identifying patterns of text (and possibly substituting them with the 
sub()
method) has many different potential applications. For example, you could:
• Find website URLs that begin with http:// or https://.
• Clean up dates in different date formats (such as 3/14/2019, 03-14-2019, 
and 2015/3/19) by replacing them with dates in a single, standard format.


184
Chapter 7
• Remove sensitive information such as Social Security or credit 
card numbers.
• Find common typos such as multiple spaces between words, acciden-
tally accidentally repeated words, or multiple exclamation marks at the 
end of sentences. Those are annoying!!
Summary
While a computer can search for text quickly, it must be told precisely what 
to look for. Regular expressions allow you to specify the pattern of charac-
ters you are looking for, rather than the exact text itself. In fact, some word 
processing and spreadsheet applications provide find-and-replace features 
that allow you to search using regular expressions.
The 
re
module that comes with Python lets you compile 
Regex
objects. 
These objects have several methods: 
search()
to find a single match, 
findall()
to find all matching instances, and 
sub()
to do a find-and-replace substitution 
of text.
You can find out more in the official Python documentation at https://
docs.python.org/3/library/re.html. Another useful resource is the tutorial 
website https://www.regular-expressions.info/.

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