Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Regex – How to Count the Number of Matches?

#1
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:



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.

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!



https://www.sickgaming.net/blog/2020/02/...f-matches/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Collections.Counter: How to Count List Elements (Python) xSicKxBot 0 1,956 08-19-2023, 06:03 AM
Last Post: xSicKxBot
  [Tut] [Fixed] Access Denied – OpenAI Error Reference Number 1020 xSicKxBot 0 1,419 08-10-2023, 09:24 PM
Last Post: xSicKxBot
  [Tut] [Fixed] Access Denied – OpenAI Error Reference Number 1020 xSicKxBot 0 1,389 05-25-2023, 04:45 PM
Last Post: xSicKxBot
  [Tut] Python Regex Capturing Groups – A Helpful Guide (+Video) xSicKxBot 0 1,418 04-07-2023, 10:07 AM
Last Post: xSicKxBot
  [Tut] How to Access Multiple Matches of a Regex Group in Python? xSicKxBot 0 1,490 04-04-2023, 02:26 PM
Last Post: xSicKxBot
  [Tut] F-String Python Hex, Oct, and Bin: Efficient Number Conversions xSicKxBot 0 1,670 03-28-2023, 12:01 PM
Last Post: xSicKxBot
  [Tut] Python | Split String with Regex xSicKxBot 0 1,414 12-13-2022, 06:04 AM
Last Post: xSicKxBot
  [Tut] Python | Split String by Number xSicKxBot 0 1,151 12-05-2022, 01:21 PM
Last Post: xSicKxBot
  [Tut] Python | Split String and Count Results xSicKxBot 0 1,161 11-26-2022, 06:39 AM
Last Post: xSicKxBot
  [Tut] How to Count the Number of Unique Values in a List in Python? xSicKxBot 0 1,350 10-19-2022, 03:08 AM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016