Python >> Tutoriel Python >  >> Python Tag >> RegEx

Python Regex Finditer()

Vous pouvez créer un itérable de tous les pattern correspond à un text en utilisant le re.finditer(pattern, text) méthode :

Spécification :re.finditer(pattern, text, flags=0)

Définition :renvoie un itérateur qui parcourt toutes les correspondances non superposées du pattern dans le text .

Le flags L'argument vous permet de personnaliser certaines propriétés avancées du moteur de regex, par exemple si la capitalisation des caractères doit être ignorée. Vous pouvez en savoir plus sur l'argument des drapeaux dans mon tutoriel de blog détaillé.

Exemple :Vous pouvez utiliser l'itérateur pour compter le nombre de correspondances. Contrairement au re.findall() méthode décrite ci-dessus, cela a l'avantage que vous pouvez analyser les objets de correspondance eux-mêmes qui contiennent beaucoup plus d'informations que la simple sous-chaîne correspondante.

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'>
'''

Si vous voulez compter le nombre de correspondances, vous pouvez utiliser un 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

Ou une solution plus Pythonique :

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

Cette méthode fonctionne très bien s'il y a des correspondances qui ne se chevauchent pas.