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 there
module 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 the beginning of a line with Python regex?
- How to match a year with Python Regex?
- How to use word boundaries in Python Regex?
- How to match a URL path using Python regex?
- How to replace all using Python regex?
- How to ignore case in Python regex?
- How to get a group from a regex in Python?
- How to match whitespace in Python regex?
- How to match a UUID using Python regex?
See more codes...