Python | How to use re.findall() in python

This post explains how to use re.findall method in Python.

re.findall function syntax

   
re.findall(pattern, string, flags=0)
 

re.findall() matches all occurrences of a pattern and returns list of matches pattern. Below are some of the examples of using re.findall in Python.

1. Extract numbers from a text using re.findall

   
import re

sample_str = 'eleven 11 ten 10 some random number 121 more numerical values 32'
ptrn_object = re.compile(r'\d+')
print(ptrn_object.findall(sample_str))  

# Output
['11', '10', '121', '32']
 

2. Extract emails from a text using re.findall

   
import re

sample_str = 'test email test@test.com, one more dummy email testing@gmail.com'

emails = re.findall(r'[\w\.-]+@[\w\.-]+', sample_str) 
for email in emails:
    print (email)     

# Output
test@test.com
testing@gmail.com
 

Follow US on Twitter: