python-regexHow to get all matches from a regex in Python?
To get all matches from a regex in Python, you can use the re.findall()
function. This function takes two arguments: the pattern to search for and the string to search in. It returns a list of all matches found.
Example code
import re
string = "The quick brown fox jumps over the lazy dog"
pattern = r"\w+"
matches = re.findall(pattern, string)
print(matches)
Output example
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
Code explanation
import re
: imports there
module which contains thefindall()
function.string = "The quick brown fox jumps over the lazy dog"
: defines the string to search in.pattern = r"\w+"
: defines the pattern to search for.matches = re.findall(pattern, string)
: calls thefindall()
function to search for the pattern in the string and store the matches in thematches
variable.print(matches)
: prints the matches found.
Helpful links
More of Python Regex
- How to replace all using Python regex?
- How to count matches with Python regex?
- How to match a year with Python Regex?
- How to perform a zero length match with Python Regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to match whitespace in Python regex?
- How to match a hex number with regex in Python?
- How to match a UUID using Python regex?
- How to match a URL path using Python regex?
See more codes...