交替與非捕捉群組

Python 中的正規表示法

Maria Eugenia Inzaugarat

Data Scientist

Pipe

  • 垂直線或 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']
Python 中的正規表示法

Pipe

  • 垂直線或 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']

Python 中的正規表示法

交替(Alternation)

  • 用群組在可選樣式間擇一

 

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']
Python 中的正規表示法

交替(Alternation)

  • 用群組在可選樣式間擇一

 

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')]
Python 中的正規表示法

非捕捉群組

  • 比對但「不捕捉」群組

    • 當群組不需反向參照時

    • 加上 ?:(?:regex)

Python 中的正規表示法

非捕捉群組

  • 比對但「不捕捉」群組

 

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']
Python 中的正規表示法

交替(Alternation)

  • 在交替中使用非捕捉群組

 

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

re.findall(r"(\d+)(?:th|rd)", my_date)
['23', '24']
Python 中的正規表示法

一起來練習吧!

Python 中的正規表示法

Preparing Video For Download...