Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ฟังก์ชัน match() ใน Python Regex (re.match)

re.match(pattern, string) พยายามจับคู่ pattern เฉพาะที่ตำแหน่งเริ่มต้นของสตริง เท่านั้น

ตัวอย่าง: จับคู่ได้ (อยู่ต้นสตริง)

>> import re
>>> result = re.match(r'TP', 'TP Tutorials Point TP')
>>> result.group(0)
'TP'

ตัวอย่าง: จับคู่ไม่ได้ (ไม่อยู่ต้นสตริง)

>> result = re.match(r'Tutorials', 'TP Tutorials Point TP')
>>> print(result)
None

การใช้งาน Match Object

>> m = re.match(r'(\w+)\s+(\w+)', 'Hello World')
>>> m.group(0)
'Hello World'
>>> m.group(1)
'Hello'
>>> m.group(2)
'World'
>>> m.groups()
('Hello', 'World')

Raw String (r'...')

ใช้ r'pattern' (raw string) เพื่อป้องกัน Python ตีความ escape sequences ก่อนส่งให้ regex engine

>> # โดยไม่มี r'...' ต้อง escape backslash สองชั้น
>>> re.match('\\d+', '123abc')   # \\ → \ ใน string → \d ใน regex
>>> re.match(r'\d+', '123abc')   # r'' → \d+ ตรงๆ เข้า regex (แนะนำ)

re.match vs re.search vs re.fullmatch

FunctionScopeUse Case
match()ต้นสตริงเท่านั้นValidate format/prefix
search()ทุกตำแหน่งค้นหา pattern ทั่วไป
fullmatch()สตริงทั้งหมดValidate format ทั้งสตริง