Regular Expression Modifiers (Flags) ควบคุมพฤติกรรมการจับคู่ ระบุผ่านพารามิเตอร์ flags หรือรวมหลาย flag ด้วย | (bitwise OR)
รายการ Flags ในโมดูล re
| Flag | ชื่อเต็ม | ความหมาย |
|---|---|---|
re.I | IGNORECASE | Case-insensitive matching |
re.L | LOCALE | ใช้ Locale ปัจจุบันสำหรับ \w, \W, \b, \B (Legacy, ไม่แนะนำ) |
re.M | MULTILINE | ^ จับคู่ต้นบรรทัด, $ จับคู่ท้ายบรรทัด (ไม่ใช่แค่ต้น/ท้าย string) |
re.S | DOTALL | . จับคู่อักขระทุกตัว รวม newline |
re.U | UNICODE | Unicode matching สำหรับ \w, \W, \b, \B (Default ใน Python 3) |
re.X | VERBOSE | Regex แบบอ่านง่าย: ignore whitespace, # เป็น comment |
ตัวอย่างการใช้งาน
re.I (IGNORECASE)
>> re.search('hello', 'HELLO WORLD', re.I)
re.M (MULTILINE)
>> import re >>> s = 'line1\nline2\nline3' >>> re.findall(r'^\w+', s) # ไม่มี flag ['line1'] >>> re.findall(r'^\w+', s, re.M) # มี flag ['line1', 'line2', 'line3']
re.S (DOTALL)
>> s = 'Line 1\nLine 2' >>> re.findall(r'.+', s) # ไม่มี flag ['Line 1', 'Line 2'] >>> re.findall(r'.+', s, re.S) # มี flag ['Line 1\nLine 2']
re.X (VERBOSE) - เขียน Regex อ่านง่าย
>> pattern = re.compile(r"""
... \d{3} # Area code
... - # Separator
... \d{4} # Number
... """, re.VERBOSE)
>>> pattern.match('123-4567')
การรวม Flags
>> re.search(pattern, string, re.I | re.M | re.S)