บทนำ
Regular Expressions (RegEx) ใช้ค้นหา แทนที่ ตรวจสอบ pattern ในข้อความ ใช้ใน text editors, search engines, validators ฯลฯ
การเริ่มต้น
module re มาพร้อม Python: import re
ฟังก์ชันหลัก
| Function | คำอธิบาย |
|---|---|
re.compile(pattern, flags) | คอมไพล์ pattern เป็น regex object (reuse ได้) |
re.search(pattern, string, flags) | ค้นหา pattern ที่ match ไหนก็ได้ใน string |
re.match(pattern, string, flags) | ตรวจสอบ match ที่ต้น string เท่านั้น |
re.split(pattern, string, maxsplit, flags) | แยก string ตาม pattern |
re.findall(pattern, string, flags) | คืน list ของทุก match |
re.finditer(pattern, string, flags) | คืน iterator ของ match objects |
re.sub(pattern, repl, string, count) | แทนที่ pattern ด้วย repl |
re.subn(pattern, repl, string, count) | เหมือน sub แต่คืน (new_string, count) |
re.escape(pattern) | escape special chars ให้เป็น literal |
ตัวอย่าง: compile + match
x = re.compile("Hello world")
y = x.match("Hello world! How are things going?")
if y: print("Strings match") # Strings matchตัวอย่าง: split
re.split(r"\W+", "Hello,World") # ['Hello', 'World'] re.split(r"(\W+)", "Hello,World") # ['Hello', ',', 'World']
ตัวอย่าง: sub / subn
re.sub(r"there", "World", "Hello there. Python is fun.")
# 'Hello World. Python is fun.'
re.subn(r"there", "World", "Hello there. Python is fun. Hello there")
# ('Hello World. Python is fun. Hello World', 2)ตัวอย่างจริง: Password Validator
import re
matching_sequence = r"[0-9]"
while True:
x = input("Enter your password: ")
r = re.search(matching_sequence, x)
if r and len(x) > 6:
print(x + " is a valid password")
else:
print(x + " is not a valid password. Password MUST be atleast 7 characters with atleast 1 number")
input("Press Enter key to exit ")สรุป
RegEx ทรงพลังแต่ซับซ้อน ควรทดสอบด้วย regex101.com และอ่านเอกสาร: https://docs.python.org/3/library/re.html