Appariement gourmand vs non gourmand

Expressions rationnelles en Python

Maria Eugenia Inzaugarat

Data Scientist

Appariement gourmand vs non gourmand

  • Deux types d’appariement :

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

Expressions rationnelles en Python

Appariement gourmand

  • Gourmand : fait correspondre un maximum de caractères

  • Renvoie la correspondance la plus longue

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

Expressions rationnelles en Python

Appariement gourmand

  • Revient en arrière si 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 rationnelles en Python

Appariement non gourmand

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

Expressions rationnelles en Python

Appariement non gourmand

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

  • Étend les correspondances un par un

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

Expressions rationnelles en Python

Passons à la pratique !

Expressions rationnelles en Python

Preparing Video For Download...