Alternation and non-capturing groups

Regular Expressions in Python

Maria Eugenia Inzaugarat

Data Scientist

Pipe

  • Vertical bar or 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

  • Vertical bar or 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

Alternation

  • Use groups to choose between optional patterns

 

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

Alternation

  • Use groups to choose between optional patterns

 

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

Non-capturing groups

  • Match but not capture a group

    • When group is not backreferenced

    • Add ?:: (?:regex)

Regular Expressions in Python

Non-capturing groups

  • Match but not capture a group

 

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

Alternation

  • Use non-capturing groups for alternation

 

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

Let's practice!

Regular Expressions in Python

Preparing Video For Download...