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

การเขียน Regular Expression แบบ Case-insensitive ใน Python โดยไม่ใช้ re.compile

สามารถส่งแฟล็ก re.IGNORECASE (หรือ re.I) ให้กับพารามิเตอร์ flags ของฟังก์ชัน search(), match(), หรือ sub() ได้โดยตรง

ตัวอย่าง

import re
print(re.search('bush', 'BuSh', re.IGNORECASE))
print(re.match('bush', 'BuSh', re.IGNORECASE))
print(re.sub('bush', 'xxxx', 'Bushmeat', flags=re.IGNORECASE))

ผลลัพธ์

<_sre.SRE_Match object at 0x...>
<_sre.SRE_Match object at 0x...>
xxxxmeat

หมายเหตุ: วิธีนี้สะดวกกว่าการใช้ re.compile(pattern, re.IGNORECASE) เมื่อต้องการใช้งานครั้งเดียวหรือไม่บ่อย