Méthode Python re.finditer()
re.finditer()est unerefonction de module pourtrouver itérativement toutes les correspondances.
Il renvoie un itérateur, où chaque élément est un objet de correspondance, vous permettant de traiter les résultats de correspondance un par un.
Définition du terme: find iterCela signifie « itérateur de recherche ».
Syntaxe de base et paramètres
Format de syntaxe
re.finditer(pattern, string, flags=0)
Description du paramètre
- pattern: Motif d'expression régulière
- string: La chaîne à rechercher
- flags: Facultatif, options d'expression régulière
Description de la fonction
- Valeur de retour: Retourne un itérateur, où chaque élément est un objet de correspondance.
- Caractéristiques: Adapté au traitement d'un grand nombre de résultats de correspondance, économisant la mémoire.
Exemples
Exemple 1 : Utilisation de base
Exemple
import re
text = "3 pommes, 5 oranges, 8 bananes"
# Itérer pour trouver tous les nombres
for match in re.finditer(r'\d+', text):
print(f"Trouvé : {match.group()} Position : {match.start()}-{match.end()}")
text = "3 pommes, 5 oranges, 8 bananes"
# Itérer pour trouver tous les nombres
for match in re.finditer(r'\d+', text):
print(f"Trouvé : {match.group()} Position : {match.start()}-{match.end()}")
Sortie attendue :
找到: 3 位置: 0-1 找到: 5 位置: 4-5 找到: 8 位置: 8-9
Exemple 2 : Traitement d'une liste d'e-mails
Exemple
import re
text = "Contactez [email protected] ou [email protected] pour obtenir de l'aide"
# Trouver et traiter chaque e-mail
for match in re.finditer(r'(\w+)@(\w+\.\w+)', text):
print(f"Complet : {match.group()}")
print(f" Nom d'utilisateur : {match.group(1)}")
print(f" Domaine : {match.group(2)}")
print(f" Position : {match.start()}-{match.end()}")
text = "Contactez [email protected] ou [email protected] pour obtenir de l'aide"
# Trouver et traiter chaque e-mail
for match in re.finditer(r'(\w+)@(\w+\.\w+)', text):
print(f"Complet : {match.group()}")
print(f" Nom d'utilisateur : {match.group(1)}")
print(f" Domaine : {match.group(2)}")
print(f" Position : {match.start()}-{match.end()}")
Sortie attendue :
完整: [email protected] 用户名: test 域名: example.com 位置: 2-16 完整: [email protected] 用户名: admin 域名: test.org 位置: 17-30
Exemple 3 : Comparaison avec re.findall()
Exemple
import re
text = "a1b2c3d4"
# findall renvoie une liste de chaînes de caractères
print("findall:", re.findall(r'\d', text))
# finditer renvoie un itérateur
print("finditer:", [m.group() for m in re.finditer(r'\d', text)])
text = "a1b2c3d4"
# findall renvoie une liste de chaînes de caractères
print("findall:", re.findall(r'\d', text))
# finditer renvoie un itérateur
print("finditer:", [m.group() for m in re.finditer(r'\d', text)])
Sortie attendue :
findall: ['1', '2', '3', '4'] finditer: ['1', '2', '3', '4']
Autres extensions
Module re de Python