Regular Expressions ใน Python
Maria Eugenia Inzaugarat
Data Scientist
วิธีการจับคู่ 2 แบบ:
Quantifier มาตรฐานเป็น greedy โดยค่าเริ่มต้น: *, +, ?, {num, num}
Greedy: จับคู่อักขระให้ได้มากที่สุด
คืนค่า ผลลัพธ์ที่ยาวที่สุด
import re
re.match(r"\d+", "12345bcada")
<re.Match object; span=(0, 5), match='12345'>

ย้อนกลับเมื่อจับคู่อักขระมากเกินไป
คืนอักขระทีละตัว
import re
re.match(r".*hello", "xhelloxxxxxx")
<re.Match object; span=(0, 6), match='xhello'>

? ต่อท้าย greedy quantifier import re
re.match(r"\d+?", "12345bcada")
<re.Match object; span=(0, 1), match='1'>

ย้อนกลับเมื่อจับคู่อักขระน้อยเกินไป
ขยายอักขระทีละตัว
import re
re.match(r".*?hello", "xhelloxxxxxx")
<re.Match object; span=(0, 6), match='xhello'>

Regular Expressions ใน Python