Python regex `findall` function
Python regex ndall() function explained with examples.
WE'LL COVER THE FOLLOWING
• Python string ndall
• Syntax
• Example 1
• Example 2: findall and Groups
Python string ndall #
findall() is a powerful function in the re module. It finds all the matches
and returns them as a list of strings, with each string representing one match.
Syntax #
[Link](pattern, string, flags=0)
The string is scanned left-to-right, and matches are returned in the order
found. If one or more groups are present in the pattern, return a list of
groups . Empty matches are included in the result unless they touch the
beginning of another match.
Example 1 #
Find all and return the email addresses:
#!/usr/bin/python
import re
line = 'your alpha@[Link], blah beta@[Link] blah user'
emails = [Link](r'[\w\.-]+@[\w\.-]+', line)
if emails:
print emails
else:
print "No match!"
Example 2: findall and Groups #
Now let’s make a second example. Groups () can be combined with
findall() . If the pattern includes 2 or more parenthesis groups, then instead
of returning a list of strings, findall() returns a list of tuples. Each tuple
represents one match of the pattern, and inside the tuple is the group(1) ,
group(2) , etc.
The following example, will find, 'alpha' , '[Link]' , 'beta' ,
and '[Link]' .
#!/usr/bin/python
import re
line = 'your alpha@[Link], blah beta@[Link] blah user'
tuples = [Link](r'([\w\.-]+)@([\w\.-]+)', line)
if tuples:
print tuples
else:
print "No match!"
Once you have the list of tuples, you can loop over it to do some computation
for each tuple.