Find all instances of a matched pattern in a string in Python

To find those parts of a string which match a pattern specified using a Regular Expression, the following code is probably the simplest.

import re

source = "A string 123 with numbers 456 and letters 789"

pattern = "[0-9]+"

results = re.findall(pattern, source)

for match in results: 
   print(match)

Result:

123
456
789

All matches of the regex inside the source string will be stored in the results list.

 

Leave a Reply

Your email address will not be published. Required fields are marked *