ใช้ anchor ^ เพื่อจับคู่ที่ ต้นสตริง (หรือต้นบรรทัดในโหมด multiline)
ตัวอย่าง: จับคำแรกในสตริง
import re s = 'cheer leaders at the football stadium' result = re.search(r'^\w+', s) print(result.group())
ผลลัพธ์
cheer
คำอธิบายรูปแบบ ^\w+
^- ตำแหน่งต้นสตริง\w+- อักขระคำ 1 ตัวขึ้นไป
จับคู่ "คำแรก" ของสตริง
โหมด Multiline (re.MULTILINE / re.M)
ด้วยแฟล็ก re.M แล้ว ^ จะจับคู่ที่ต้น ทุกบรรทัด
>> import re >>> s = 'line one\nline two\nline three' >>> re.findall(r'^\w+', s) # ไม่มี flag ['line'] >>> re.findall(r'^\w+', s, re.M) # มี flag MULTILINE ['line', 'line', 'line']