分组与捕获

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 中的正则表达式

Vamos praticar!

Python 中的正则表达式

Preparing Video For Download...