How to: Count your regex pattern matches in python

| No Comments »

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!

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

Leave a Reply