Alternatie en niet-capturerende groepen

Regular expressions in Python

Maria Eugenia Inzaugarat

Data Scientist

Pipe

  • Verticale streep of 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']
Regular expressions in Python

Pipe

  • Verticale streep of 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']

Regular expressions in Python

Alternatie

  • Gebruik groepen om tussen optionele patronen te kiezen

 

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']
Regular expressions in Python

Alternatie

  • Gebruik groepen om tussen optionele patronen te kiezen

 

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')]
Regular expressions in Python

Niet-capturerende groepen

  • Match maar capture de groep niet

    • Als de groep niet wordt terugverwezen

    • Voeg ?: toe: (?:regex)

Regular expressions in Python

Niet-capturerende groepen

  • Match een groep maar capture niet

 

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']
Regular expressions in Python

Alternatie

  • Gebruik niet-capturerende groepen voor alternatie

 

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

re.findall(r"(\d+)(?:th|rd)", my_date)
['23', '24']
Regular expressions in Python

Laten we oefenen!

Regular expressions in Python

Preparing Video For Download...