Alternance et groupes non capturants

Expressions régulières en Python

Maria Eugenia Inzaugarat

Data Scientist

Pipe

  • Barre verticale ou « pipe » : |

 

my_string = "I want to have a pet. But I don't know if I want a cat, a dog or a bird."

re.findall(r"cat|dog|bird", my_string)
['cat', 'dog', 'bird']
Expressions régulières en Python

Pipe

  • Barre verticale ou « pipe » : |

   

my_string = "I want to have a pet. But I don't know if I want 2 cats, 1 dog or a bird."

re.findall(r"\d+\scat|dog|bird", my_string)
['2 cat', 'dog', 'bird']

Expressions régulières en Python

Alternance

  • Utilisez des groupes pour choisir entre des motifs optionnels

 

my_string = "I want to have a pet. But I don't know if I want 2 cats, 1 dog or a bird."
re.findall(r"\d+\s(cat|dog|bird)", my_string)
['cat', 'dog']
Expressions régulières en Python

Alternance

  • Utilisez des groupes pour choisir entre des motifs optionnels

 

my_string = "I want to have a pet. But I don't know if I want 2 cats, 1 dog or a bird."

re.findall(r"(\d)+\s(cat|dog|bird)", my_string)
[('2', 'cat'), ('1', 'dog')]
Expressions régulières en Python

Groupes non capturants

  • Faire correspondre sans capturer un groupe

    • Quand le groupe n'est pas référencé ensuite

    • Ajouter ?: : (?:regex)

Expressions régulières en Python

Groupes non capturants

  • Faire correspondre sans capturer un groupe

 

my_string = "John Smith: 34-34-34-042-980, Rebeca Smith: 10-10-10-434-425"

re.findall(r"(?:\d{2}-){3}(\d{3}-\d{3})", my_string)
['042-980', '434-425']
Expressions régulières en Python

Alternance

  • Utilisez des groupes non capturants pour l'alternance

 

my_date = "Today is 23rd May 2019. Tomorrow is 24th May 19."

re.findall(r"(\d+)(?:th|rd)", my_date)
['23', '24']
Expressions régulières en Python

Passons à la pratique !

Expressions régulières en Python

Preparing Video For Download...