Python Regular Expression (re)
Regular Expression (regex) คือภาษาเล็ก ๆ สำหรับอธิบาย “รูปแบบ” ของข้อความ ใช้ค้นหา ตรวจสอบ หรือแยกส่วนข้อความที่มีแบบแผน เช่น อีเมล เบอร์โทร รหัสไปรษณีย์ วันที่ Python มี module re มาให้
เริ่มต้น
import re
text = "ติดต่อ support@example.com หรือ sales@example.com"
emails = re.findall(r"[\w.]+@[\w.]+", text)
print(emails) # ['support@example.com', 'sales@example.com']r"..." คือ raw string ทำให้ \ ไม่ถูกตีความ ใช้กับ regex เสมอ
metacharacter ที่ต้องรู้
| สัญลักษณ์ | ความหมาย |
|---|---|
. | อักขระอะไรก็ได้ 1 ตัว (ยกเว้นขึ้นบรรทัดใหม่) |
\d | ตัวเลข 0-9 |
\w | ตัวอักษร ตัวเลข หรือ _ |
\s | ช่องว่าง (space, tab, newline) |
\D \W \S | ตรงข้ามกับตัวเล็ก |
^ | ต้นข้อความ |
$ | ท้ายข้อความ |
[abc] | ตัวใดตัวหนึ่งใน a, b, c |
[^abc] | ตัวที่ไม่ใช่ a, b, c |
[0-9] [ก-๙] | ช่วง |
| | หรือ (cat|dog) |
ตัวบอกจำนวนครั้ง (quantifier)
| สัญลักษณ์ | ความหมาย |
|---|---|
* | 0 ครั้งขึ้นไป |
+ | 1 ครั้งขึ้นไป |
? | 0 หรือ 1 ครั้ง |
{3} | 3 ครั้งพอดี |
{2,4} | 2 ถึง 4 ครั้ง |
{2,} | 2 ครั้งขึ้นไป |
import re
print(re.findall(r"\d+", "มี 3 แมว 12 หมา")) # ['3', '12']
print(re.findall(r"\d{4}", "ปี 2024 และ 2026")) # ['2024', '2026']
print(re.findall(r"a?bc", "bc abc")) # ['bc', 'abc']ฟังก์ชันหลักใน re
re.search — หาที่แรกที่เจอ
import re
m = re.search(r"\d+", "ราคา 250 บาท")
if m:
print(m.group()) # 250
print(m.start()) # 5 ตำแหน่งที่เจอคืน match object ถ้าเจอ, คืน None ถ้าไม่เจอ
re.match — ตรงกับต้นข้อความไหม
print(re.match(r"\d+", "123abc")) # match (เจอที่ต้น)
print(re.match(r"\d+", "abc123")) # None (ต้นไม่ใช่ตัวเลข)re.findall — เอาทุกที่ที่เจอเป็นลิสต์
text = "โทร 081-234-5678 หรือ 02-111-2222"
print(re.findall(r"\d[\d-]+\d", text))
# ['081-234-5678', '02-111-2222']re.sub — ค้นแล้วแทนที่
text = "ราคา 1000 บาท ลด 200 บาท"
# ปิดตัวเลขทั้งหมด
print(re.sub(r"\d+", "XXX", text))
# ราคา XXX บาท ลด XXX บาท
# ลบช่องว่างเกิน
messy = "คำ เยอะ ช่องว่าง"
print(re.sub(r"\s+", " ", messy))
# คำ เยอะ ช่องว่างre.split — แยกด้วยรูปแบบ
text = "แอปเปิล, กล้วย;ส้ม องุ่น"
print(re.split(r"[,;\s]+", text))
# ['แอปเปิล', 'กล้วย', 'ส้ม', 'องุ่น']จับกลุ่มด้วยวงเล็บ
วงเล็บ () “จับ” ส่วนที่ต้องการดึงออกมา
import re
text = "วันที่ 06/09/2026"
m = re.search(r"(\d{2})/(\d{2})/(\d{4})", text)
if m:
day, month, year = m.groups()
print(day, month, year) # 06 09 2026
print(m.group(1)) # 06
print(m.group(0)) # 06/09/2026 (ทั้งหมด)ตั้งชื่อกลุ่ม
pattern = r"(?P<user>[\w.]+)@(?P<domain>[\w.]+)"
m = re.search(pattern, "ส่งถึง john.doe@company.com")
print(m.group("user")) # john.doe
print(m.group("domain")) # company.comfindall กับกลุ่ม
ถ้ามีกลุ่ม findall คืนเป็นทูเพิลของกลุ่ม
text = "a=1, b=2, c=3"
print(re.findall(r"(\w)=(\d)", text))
# [('a', '1'), ('b', '2'), ('c', '3')]compile: ใช้ pattern ซ้ำ
ถ้าใช้ pattern เดิมหลายครั้ง compile ไว้ก่อนจะเร็วกว่าและอ่านชัดกว่า
import re
email_pattern = re.compile(r"^[\w.+-]+@[\w-]+\.[\w.-]+$")
def is_valid_email(email):
return email_pattern.match(email) is not None
print(is_valid_email("test@example.com")) # True
print(is_valid_email("not-an-email")) # Falseตัวอย่างรวม: ดึงข้อมูลจาก log
import re
log = """
2026-09-06 14:30:12 ERROR การเชื่อมต่อล้มเหลว
2026-09-06 14:30:15 INFO เชื่อมต่อสำเร็จ
2026-09-06 14:31:02 ERROR timeout
"""
pattern = re.compile(
r"(?P<date>\d{4}-\d{2}-\d{2}) "
r"(?P<time>\d{2}:\d{2}:\d{2}) "
r"(?P<level>\w+) "
r"(?P<message>.+)"
)
for line in log.strip().splitlines():
m = pattern.match(line)
if m and m.group("level") == "ERROR":
print(f"[{m.group('time')}] {m.group('message')}")ผลลัพธ์:
[14:30:12] การเชื่อมต่อล้มเหลว
[14:31:02] timeoutเตือน
- regex ที่ซับซ้อนมากอ่านยากและ debug ยาก บางงานใช้
str.split()/str.replace()/inก็พอ - อย่าใช้ regex parse HTML หรือ JSON ใช้ไลบรารีเฉพาะทาง
- ทดสอบ pattern ได้ที่เว็บอย่าง regex101.com
เช็คความเข้าใจก่อนข้ามบท
- แยกได้ว่า pattern, metacharacter และ quantifier คืออะไร
- ใช้
re.search,re.findall,re.subในโจทย์พื้นฐานได้ - ลองเขียน regex ตรวจเบอร์โทรหรืออีเมลแบบง่าย พร้อมทดสอบทั้งเคสผ่านและไม่ผ่าน
สรุป
re.searchหาที่แรก,re.findallเอาทุกที่,re.subแทนที่,re.splitแยก\d \w \sแทนกลุ่มอักขระ,* + ? {n,m}บอกจำนวนครั้ง,^ $ยึดต้น/ท้าย()จับกลุ่ม เข้าถึงด้วย.group(n)หรือตั้งชื่อ(?P<name>...)- ใช้ raw string
r"..."เสมอ และre.compileเมื่อใช้ซ้ำ
บทถัดไปว่าด้วยการทำงานกับวันและเวลาแบบละเอียด