Python re.findall() Method
re.findall()is Pythonrein the module, used tofind all matchesfunction.
It scans the entire string and returns all substrings that match the regular expression, in the form of a list.
Word Definitions: find allIt means 'find all'.
Basic Syntax and Parameters
re.findall()It is a module-level function.
Syntax Format
re.findall(pattern, string, flags=0)
Parameter Description
- pattern: regular expression pattern
- string: the string to be searched
- flags: optional, regular expression flags
Function Description
- Return Value: Returns a list containing all matched strings. If there is no match, returns an empty list.
- Features: Returns all matches, not just the first one.
Examples
Example 1: Find All Numbers
Example
import re
text = I have 3 apples, 5 oranges, 8 bananas
# Find all numbers
result = re.findall(r'\d+', text)
print(Numbers found:, result)
text = I have 3 apples, 5 oranges, 8 bananas
# Find all numbers
result = re.findall(r'\d+', text)
print(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)
print(Python found:, result)
text = "Python is powerful, Python is easy"
# Find all "Python"
result = re.findall(r'Python', text)
print(Python found:, result)
Expected output:
找到的Python: ['Python', 'Python']
Example 3: Use Groups to Extract Multiple Contents
Example
import re
text = Email: [email protected], Email: [email protected]
# Use groups to extract username and domain at the same time
result = re.findall(r'(\w+)@(\w+\.\w+)', text)
print(Emails found:, result)
text = Email: [email protected], Email: [email protected]
# Use groups to extract username and domain at the same time
result = re.findall(r'(\w+)@(\w+\.\w+)', text)
print(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)
print(All phone numbers:, result)
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)
print(All phone numbers:, result)
Expected output:
所有手机号: ['138-1234-5678', '139-9876-5432', '137-5555-8888']
Other Extensions
Python re Module