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ə11/25
tarix29.11.2022
ölçüsü397,03 Kb.
#71308
1   ...   7   8   9   10   11   12   13   14   ...   25
P A T T E R N M A T C H I N G W I T H

The findall() Method
In addition to the 
search()
method, 
Regex
objects also have a 
findall()
method. While 
search()
will return a 
Match
object of the first matched text 
in the searched string, the 
findall()
method will return the strings of every 


172
Chapter 7
match in the searched string. To see how 
search()
returns a 
Match
object 
only on the first instance of matching text, enter the following into the 
interactive shell:
>>> phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
>>> mo = phoneNumRegex.search('Cell: 415-555-9999 Work: 212-555-0000')
>>> mo.group()
'415-555-9999'
On the other hand, 
findall()
will not return a 
Match
object but a list of 
strings—as long as there are no groups in the regular expression. Each string in 
the list is a piece of the searched text that matched the regular expression. 
Enter the following into the interactive shell:
>>> phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') # has no groups
>>> phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000')
['415-555-9999', '212-555-0000']
If there are groups in the regular expression, then 
findall()
will return 
a list of tuples. Each tuple represents a found match, and its items are the 
matched strings for each group in the regex. To see 
findall()
in action, 
enter the following into the interactive shell (notice that the regular expres-
sion being compiled now has groups in parentheses):
>>> phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)') # has groups
>>> phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000')
[('415', '555', '9999'), ('212', '555', '0000')]
To summarize what the 
findall()
method returns, remember the 
following:
• When called on a regex with no groups, such as 
\d\d\d-\d\d\d-\d\
d\d\d
, the method 
findall()
returns a list of string matches, such as 
['415-555-9999', '212-555-0000']
.
• When called on a regex that has groups, such as 
(\d\d\d)-(\d\d\d) 
-(\d\d\d\d)
, the method 
findall()
returns a list of tuples of strings 
(one string for each group), such as 
[('415', '555', '9999'), ('212', 
'555', '0000')]
.

Yüklə 397,03 Kb.

Dostları ilə paylaş:
1   ...   7   8   9   10   11   12   13   14   ...   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