How to: Count your regex pattern matches in python

Problem: I need to display the number of times my regex has matched.

Solution: No Problem! Use the len (abbrev. for length) function:

import re
>>> regex = re.compile(r”your pattern here…*”)
>>> match = regex.findall(”the contents…”)
>>> len(match)
10

That’s It!

120x20 thumb black How to: Count your regex pattern matches in python

On a side note, you can also use len to count the number of characters in a string.

>>> text = “All your base…”
>>> len(text)
16

Some links that you might find useful [External]:

Still can't see what you're looking for?



Was this helpful? Post your comments here!

Anti-Spam Protection by WP-SpamFree