Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Hàm match() trong module re Python

re.match(pattern, string) chỉ kiểm tra pattern có khớp ở đầu chuỗi hay không.

Cú pháp

re.match(pattern, string, flags=0)

Ví dụ

import re
s = 'TP Tutorials Point TP'

# Khớp ở đầu
re.match(r'TP', s).group()      # 'TP'

# Không khớp ở đầu
re.match(r'Tutorials', s)       # None

# In match object
re.match(r'TP', s)
# <_sre.SRE_Match object at 0x...>

Match object → chuỗi

m = re.match(r'TP', s)
print(m.group(0))  # 'TP'
print(m.group())   # 'TP' (mặc định group 0)

Raw string (r'...')

Luôn dùng raw string cho regex pattern để tránh escape backslash:

re.match(r'\d+', '123abc')  # đúng
re.match('\d+', '123abc')   # sai: \d thành 'd' trong string thường