Nhóm và bắt giữ

Regular Expressions in Python

Maria Eugenia Inzaugarat

Data Scientist

Nhóm ký tự

 

Regular Expressions in Python

Nhóm ký tự

 

 

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']
Regular Expressions in Python

Nhóm bắt giữ

 

  • Dùng ngoặc đơn để nhómbắt ký tự cùng nhau

 

Regular Expressions in Python

Nhóm bắt giữ

 

  • Dùng ngoặc đơn để nhóm và bắt ký tự cùng nhau

 

re.findall(r'([A-Za-z]+)\s\w+\s\d+\s\w+', text)
['Clary', 'Susan', 'John']
Regular Expressions in Python

Nhóm bắt giữ

 

 

Regular Expressions in Python

Nhóm bắt giữ

 

 

re.findall(r'([A-Za-z]+)\s\w+\s(\d+)\s(\w+)', text)
[('Clary', '2', 'friends'),
 ('Susan', '3', 'brothers'),
 ('John', '4', 'sisters')]
Regular Expressions in Python

Nhóm bắt giữ

  • Khớp một mẫu con cụ thể trong mẫu
  • Dùng cho xử lý tiếp theo
Regular Expressions in Python

Nhóm bắt giữ

  • Tổ chức dữ liệu
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'
Regular Expressions in Python

Nhóm bắt giữ

  • Áp dụng cho ký tự ở bên trái ngay lập tức

    • r"apple+": + áp dụng cho e, không phải cho apple

 

  • Áp dụng lượng từ cho toàn bộ nhóm
re.search(r"(\d[A-Za-z])+", "My user name is 3e4r5fg")
<re.Match object; span=(16, 22), match='3e4r5f'>
Regular Expressions in Python

Nhóm bắt giữ

  • Bắt một nhóm lặp (\d+) so với lặp một nhóm bắt giữ (\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']
Regular Expressions in Python

Ayo berlatih!

Regular Expressions in Python

Preparing Video For Download...