Appariement gourmand vs non gourmand

Expressions régulières en Python

Maria Eugenia Inzaugarat

Data Scientist

Appariement gourmand vs non gourmand

  • Deux types d'appariement :

    • Gourmand
    • Non gourmand (lazy)
  • Les quantificateurs standards sont gourmands par défaut : *, +, ?, {num, num}

Expressions régulières en Python

Appariement gourmand

  • Gourmand : fait correspondre le plus de caractères possible

  • Retourne la correspondance la plus longue

import re
re.match(r"\d+", "12345bcada")
<re.Match object; span=(0, 5), match='12345'>

Expressions régulières en Python

Appariement gourmand

  • Revient en arrière quand trop de caractères correspondent

  • Abandonne les caractères un par un

import re
re.match(r".*hello", "xhelloxxxxxx")
<re.Match object; span=(0, 6), match='xhello'>

Expressions régulières en Python

Appariement non gourmand

  • Non gourmand (lazy) : fait correspondre le minimum nécessaire
  • Retourne la correspondance la plus courte
  • Ajouter ? aux quantificateurs gourmands
import re
re.match(r"\d+?", "12345bcada")
<re.Match object; span=(0, 1), match='1'>

Expressions régulières en Python

Appariement non gourmand

  • Revient en arrière quand trop peu de caractères correspondent

  • Étend les caractères un à la fois

import re
re.match(r".*?hello", "xhelloxxxxxx")
<re.Match object; span=(0, 6), match='xhello'>

Expressions régulières en Python

Passons à la pratique !

Expressions régulières en Python

Preparing Video For Download...