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

การจับคู่ที่ท้ายสตริงใน Python Regex (Anchor $)

ใช้ anchor $ เพื่อจับคู่ที่ ท้ายสตริง (หรือท้ายบรรทัดในโหมด multiline)

ตัวอย่าง: จับคำสุดท้ายในสตริง

import re
s = 'cheer leaders at the football stadium'
result = re.search(r'\w+$', s)
print(result.group())

ผลลัพธ์

stadium

คำอธิบายรูปแบบ \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
['three']
>>> re.findall(r'\w+$', s, re.M)     # มี flag MULTILINE
['one', 'two', 'three']