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

Regular Expression Modifiers (Flags) ใน Python

Regular Expression Modifiers (Flags) ควบคุมพฤติกรรมการจับคู่ ระบุผ่านพารามิเตอร์ flags หรือรวมหลาย flag ด้วย | (bitwise OR)

รายการ Flags ในโมดูล re

Flagชื่อเต็มความหมาย
re.IIGNORECASECase-insensitive matching
re.LLOCALEใช้ Locale ปัจจุบันสำหรับ \w, \W, \b, \B (Legacy, ไม่แนะนำ)
re.MMULTILINE^ จับคู่ต้นบรรทัด, $ จับคู่ท้ายบรรทัด (ไม่ใช่แค่ต้น/ท้าย string)
re.SDOTALL. จับคู่อักขระทุกตัว รวม newline
re.UUNICODEUnicode matching สำหรับ \w, \W, \b, \B (Default ใน Python 3)
re.XVERBOSERegex แบบอ่านง่าย: 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)