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
| Function | Scope | Use Case |
|---|---|---|
match() | ต้นสตริงเท่านั้น | Validate format/prefix |
search() | ทุกตำแหน่ง | ค้นหา pattern ทั่วไป |
fullmatch() | สตริงทั้งหมด | Validate format ทั้งสตริง |