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 theremodule 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 thematchesvariable.print(matches): prints the matches found.
Helpful links
More of Python Regex
- How to match a YYYY-MM-DD date with Python Regex?
- How to match a year with Python Regex?
- How to match whitespace in Python regex?
- How to match a UUID using Python regex?
- How to match a question mark in Python regex?
- How to use word boundaries in Python Regex?
- How to match a plus sign in Python regex?
- How to match a hex number with regex in Python?
- How to regex match excluding a word in Python?
- How to split using Python regex?
See more codes...