Alternância e grupos não capturantes

Expressões regulares em Python

Maria Eugenia Inzaugarat

Data Scientist

Pipe

  • Barra vertical 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']
Expressões regulares em Python

Pipe

  • Barra vertical 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']

Expressões regulares em Python

Alternância

  • Use grupos para escolher entre padrões opcionais

 

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']
Expressões regulares em Python

Alternância

  • Use grupos para escolher entre padrões opcionais

 

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')]
Expressões regulares em Python

Grupos não capturantes

  • Corresponder mas não capturar um grupo

    • Quando o grupo não tem retroreferência

    • Adicione ?:: (?:regex)

Expressões regulares em Python

Grupos não capturantes

  • Corresponder mas não capturar um grupo

 

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']
Expressões regulares em Python

Alternância

  • Use grupos não capturantes para alternância

 

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

re.findall(r"(\d+)(?:th|rd)", my_date)
['23', '24']
Expressões regulares em Python

Vamos praticar!

Expressões regulares em Python

Preparing Video For Download...