Alternace a nezachycující skupiny

Regular Expressions in Python

Maria Eugenia Inzaugarat

Data Scientist

Roura

  • Svislá čára nebo roura: |

 

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

Roura

  • Svislá čára nebo roura: |

   

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

Alternace

  • Použití skupin pro výběr mezi volitelnými vzory

 

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

Alternace

  • Použití skupin pro výběr mezi volitelnými vzory

 

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

Nezachycující skupiny

  • Skupinu zachytit, ale nezachycovat

    • Pokud skupina není zpětně referencována

    • Přidat ?:: (?:regex)

Regular Expressions in Python

Nezachycující skupiny

  • Skupinu zachytit, ale nezachycovat

 

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

Alternace

  • Použití nezachycujících skupin pro alternaci

 

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

Lass uns üben!

Regular Expressions in Python

Preparing Video For Download...