Regular Expression (Regex) คือลำดับของอักขระที่กำหนด Search Pattern ใช้สำหรับค้นหา จับคู่ แยก และแทนที่ข้อความในสตริงหรือไฟล์ รองรับในภาษาโปรแกรมส่วนใหญ่ (Python, Perl, Java, JavaScript, R, Go, ฯลฯ)
หลักการพื้นฐาน
- ทุกอย่างคือ อักขระ (Character)
- เขียน Pattern เพื่อจับคู่ ลำดับอักขระเฉพาะ (String)
- ใช้ ASCII ธรรมดา (ตัวอักษร ตัวเลข สัญลักษณ์) หรือ Unicode สำหรับข้อความระหว่างประเทศ
โมดูล re ใน Python
Python มีโมดูล re สำหรับ Regular Expressions ต้อง import re ก่อนใช้งาน
การใช้งานหลัก 4 แบบ
| Operation | Function | คำอธิบาย |
|---|---|---|
| Search | re.search() | ค้นหา pattern ที่ไหนก็ได้ในสตริง คืน Match object แรก |
| Match | re.match() | จับคู่ pattern ที่ต้นสตริงเท่านั้น |
| Find All | re.findall() | ค้นหา ทุกครั้ง ที่จับคู่ คืน List ของ strings |
| Split | re.split() | แบ่งสตริงด้วย pattern เป็น delimiter |
| Substitute | re.sub() | แทนที่ pattern ด้วย string ใหม่ |
ตัวอย่างเบื้องต้น
>> import re
>>> text = "Email: user@example.com, Phone: 081-234-5678"
# Find all emails
>>> re.findall(r'[\w.+-]+@[\w-]+\.[\w.-]+', text)
['user@example.com']
# Replace phone numbers
>>> re.sub(r'\d{3}-\d{3}-\d{4}', '[PHONE]', text)
'Email: user@example.com, Phone: [PHONE]'
# Split by punctuation
>>> re.split(r'[,.]', 'a,b.c,d')
['a', 'b', 'c', 'd']
แนวทางปฏิบัติที่ดี
- ใช้ Raw String
r'pattern'เสมอ - Compile pattern ด้วย
re.compile()หากใช้ซ้ำหลายครั้ง - ใช้ Flags (
re.I,re.M,re.S,re.X) ตามความเหมาะสม - ทดสอบ Regex ด้วยเครื่องมือออนไลน์ (regex101.com, regexr.com)