Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python re.findall() Method

Python re.findall() Method

Python re Module Python re Module


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

Function description


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

)

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

)

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

)

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

)

Expected output:

所有手机号: ['138-1234-5678', '139-9876-5432', '137-5555-8888']

Python re Module Python re Module