python-regexHow to count matches with Python regex?
Python regex can be used to count matches in a string. To do this, the re.findall() function can be used. This function returns a list of all matches in the string.
Example code
import re
string = "This is a string with some words"
matches = re.findall(r"\w+", string)
print(matches)
Output example
['This', 'is', 'a', 'string', 'with', 'some', 'words']
Code explanation
import re: imports theremodule which contains thefindall()functionre.findall(r"\w+", string): uses thefindall()function to find all matches of the regex pattern\w+in the stringprint(matches): prints the list of matches
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 use word boundaries in Python Regex?
- How to match a URL using Python regex?
- How to match whitespace in Python regex?
- How to match a UUID using Python regex?
- How to get a group from a regex in Python?
- How to make a case insensitive match with Python regex?
- How to match any symbol except a given one with Python regex?
- How to replace a certain group using Python regex?
See more codes...