Python Regex – How to Count the Number of Matches?

I just wrote a regular expression in Python that matches multiple times in the text and wondered: how to count the number of matches?

Consider the example where you match an arbitrary number of word characters '[a-z]+' in a given sentence 'python is the best programming language in the world'.

You can watch my explainer video as you read over the tutorial:

Related article: Python Regex Superpower – The Ultimate Guide

Google, Facebook, and Amazon engineers are regular expression masters. If you want to become one as well, check out our new book: The Smartest Way to Learn Python Regex (Amazon Kindle/Print, opens in new tab).

How many matches are there in the string? To count the number of matches, you can use multiple methods:

1. Python re.findall()

Use the re.findall(pattern, string) method that returns a list of matching substrings. Then count the length of the returned list. Here’s an example:

>>> import re
>>> pattern = '[a-z]+'
>>> text = 'python is the best programming language in the world'
>>> len(re.findall(pattern, text))
9

Why is the result 9? Because there are nine matching substrings in the returned list of the re.findall() method:

>>> re.findall(pattern, text)
['python', 'is', 'the', 'best', 'programming', 'language', 'in', 'the', 'world']

This method works great if there are non-overlapping matches.

Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.

2. Python re.finditer()

You can also count the number of times a given pattern matches in a text by using the re.finditer(pattern, text) method:

Specification: re.finditer(pattern, text, flags=0)

Definition: returns an iterator that goes over all non-overlapping matches of the pattern in the text.

The flags argument allows you to customize some advanced properties of the regex engine such as whether capitalization of characters should be ignored. You can learn more about the flags argument in my detailed blog tutorial.

Example: You can use the iterator to count the number of matches. In contrast to the re.findall() method described above, this has the advantage that you can analyze the match objects themselves that carry much more information than just the matching substring.

import re
pattern = '[a-z]+'
text = 'python is the best programming language in the world'
for match in re.finditer(pattern, text):
   print(match)

'''
<re.Match object; span=(0, 6), match='python'>
<re.Match object; span=(7, 9), match='is'>
<re.Match object; span=(10, 13), match='the'>
<re.Match object; span=(14, 18), match='best'>
<re.Match object; span=(19, 30), match='programming'>
<re.Match object; span=(31, 39), match='language'>
<re.Match object; span=(40, 42), match='in'>
<re.Match object; span=(43, 46), match='the'>
<re.Match object; span=(47, 52), match='world'>
'''

If you want to count the number of matches, you can use a simple count variable:

import re
pattern = '[a-z]+'
text = 'python is the best programming language in the world'

count = 0
for match in re.finditer(pattern, text):
   count += 1

print(count)
# 9

Or a more Pythonic solution:

import re
pattern = '[a-z]+'
text = 'python is the best programming language in the world'

print(len([i for i in re.finditer(pattern, text)]))
# 9

This method works great if there are non-overlapping matches.

3. Overlapping Matches

The above two methods work great if there are no overlapping matches. If there are overlapping matches, the regex engine will just ignore them because it “consumes” the whole matching substrings and starts matching the next pattern only after the stop index of the previous match.

So if you need to find the number of overlapping matches, you need to use a different approach.

The idea is to keep track of the start position in the previous match and increment it by one after each match:

import re
pattern = '99'
text = '999 ways of writing 99 - 99999'

left = 0
count = 0
while True:
    match = re.search(pattern, text[left:])
    if not match:
        break
    count += 1
    left += match.start() + 1
print(count)
# 7    

By keeping track of the start index of the previous match in the left variable, we can control where to look for the next match in the string. Note that we use Python’s slicing operation text[left:] to ignore all left characters that are already considered in previous matches. In each loop iteration, we match another pattern in the text. This works even if those matches overlap.

Where to Go From Here

You’ve learned three ways of finding the number of matches of a given pattern in a string.

If you struggle with regular expressions, check out our free 20,000 word regex tutorial on the Finxter blog! It’ll give you regex superpowers!