รูปแบบ ฟังก์ชั่น match ของ โมดูล re ใน Python
รูปแบบ
re.match(pattern, string, flags=0)
pattern คือ รูปแบบต้องที่เรากำหนดเพื่อหาความเหมือนในข้อความ
string คือข้อความที่ต้องการค้นหา
flags คือรูปแบบในการค้นหาดูได้ตามตาราง Python Regular Expressions flags options
คือค่า ฟังก์ชั่นจะคืนค่า object ที่เหมือนออกมา และ None ถ้าไม่เจอ
ตัวอย่าง regular_expressions.py
import re
# re.match(pattern, string, flags=0)
str = "ทดสอบ are smarter than dogs 3"
# ตัด .* ออกเพื่อให้ไม่เอาว่าตรงคำใดๆ ลงท้าย
matchObj = re.match( r'(.*) than (.*?)(.*)', str, re.M|re.I)
if matchObj:
print ("matchObj.group() : ", matchObj.group())
print ("matchObj.group(1) : ", matchObj.group(1))
print ("matchObj.group(2) : ", matchObj.group(2))
print ("matchObj.groups : ", matchObj.groups())
else:
print ("No match!!")
# retrun match ตาม (.*) เป็น tuple
for t in matchObj.groups():
print(t)
ผลที่ได้
matchObj.group() : ทดสอบ are smarter than dogs 3
matchObj.group(1) : ทดสอบ are smarter
matchObj.group(2) :
matchObj.groups : ('ทดสอบ are smarter', '', 'dogs 3')
ทดสอบ are smarter
dogs 3