Python re.findall() Method
re.findall() is a function in the Python re module used toFind all matches.
It scans the entire string and returns all substrings matching the regular expression as a list.
Word meaning: find all means "find all".
Basic syntax and parameters
re.findall() is a module-level function.
Syntax format
re.findall(pattern, string, flags=0)
Parameter Description
- pattern: The regular expression pattern
- string: The string to search
- flags: Optional, regular expression flags
Function description
- Return Value: Returns a list containing all matching strings. If there is no match, an empty list is returned.
- Feature: Returns all matches, not just the first one.
Example
Example 1: find all numbers
Example
import
re
text
=
"I have 3 apples, 5 oranges, and 8 bananas"
Find all numbers
result
=
re
.
findall
(
r
'\d+'
,
text
)
(
"Numbers found:"
,
result
)
Expected output:
找到的数字: ['3', '5', '8']
Example 2: find all words
Example
import
re
text
=
"Python is powerful, Python is easy"
Find all "Python"
result
=
re
.
findall
(
r
'Python'
,
text
)
(
"Python found:"
,
result
)
Expected output:
找到的Python: ['Python', 'Python']
Example 3: use groups to extract multiple pieces of content
Example
import
re
text
=
"Email: test@example.com, Email: admin@test.org"
Use groups to extract both the username and the domain
result
=
re
.
findall
(
r
'(\w+)@(\w+.\w+)'
,
text
)
(
"Emails found:"
,
result
)
Expected output:
找到的邮箱: [('test', 'example.com'), ('admin', 'test.org')]
Example 4: find all phone numbers
Example
import
re
text
=
"Zhang San: 138-1234-5678, Li Si: 139-9876-5432, Wang Wu: 137-5555-8888"
Find all phone numbers
result
=
re
.
findall
(
r
'\d{3}-\d{4}-\d{4}'
,
text
)
(
"All phone numbers:"
,
result
)
Expected output:
所有手机号: ['138-1234-5678', '139-9876-5432', '137-5555-8888']
Python re Module