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 question mark in Python regex?
- How to use word boundaries in Python Regex?
- How to match a year with Python Regex?
- How to match a plus sign in Python regex?
- How to match a hex number with regex in Python?
- How to match whitespace in Python regex?
- How to replace all using Python regex?
- How to match any symbol except a given one with Python regex?
- How to replace in a file using Python regex?
See more codes...