分組與捕捉

Python 中的正規表示法

Maria Eugenia Inzaugarat

Data Scientist

分組字元

 

Python 中的正規表示法

分組字元

 

 

re.findall(r'[A-Za-z]+\s\w+\s\d+\s\w+', text)
['Clary has 2 friends', 'Susan has 3 brothers', 'John has 4 sisters']
Python 中的正規表示法

捕捉群組

 

  • 用括號將字元一起「分組」並「捕捉」

 

Python 中的正規表示法

捕捉群組

 

  • 使用括號將字元分組並一起捕捉

 

re.findall(r'([A-Za-z]+)\s\w+\s\d+\s\w+', text)
['Clary', 'Susan', 'John']
Python 中的正規表示法

捕捉群組

 

 

Python 中的正規表示法

捕捉群組

 

 

re.findall(r'([A-Za-z]+)\s\w+\s(\d+)\s(\w+)', text)
[('Clary', '2', 'friends'),
 ('Susan', '3', 'brothers'),
 ('John', '4', 'sisters')]
Python 中的正規表示法

捕捉群組

  • 在樣式中比對特定子樣式
  • 供後續處理使用
Python 中的正規表示法

捕捉群組

  • 組織資料
pets = re.findall(r'([A-Za-z]+)\s\w+\s(\d+)\s(\w+)', "Clary has 2 dogs but John has 3 cats")

pets[0][0]
'Clary'
Python 中的正規表示法

捕捉群組

  • 量詞作用在「左邊緊鄰」的單位

    • r"apple+"+ 只套用在 e,而不是 apple

 

  • 將量詞套用到整個群組
re.search(r"(\d[A-Za-z])+", "My user name is 3e4r5fg")
<re.Match object; span=(16, 22), match='3e4r5f'>
Python 中的正規表示法

捕捉群組

  • 捕捉重複的群組 (\d+) vs. 重複一個捕捉群組 (\d)+
my_string = "My lucky numbers are 8755 and 33"
re.findall(r"(\d)+", my_string)
['5', '3']

 

re.findall(r"(\d+)", my_string)
['8755', '33']
Python 中的正規表示法

一起來練習吧!

Python 中的正規表示法

Preparing Video For Download...