Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!

Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount

นิพจน์ตามปกติ


Regular Expressions (บางครั้งย่อว่า regexp, regex, หรือ re) เป็นเครื่องมือในการจับคู่รูปแบบในข้อความ ใน Python, เรามีโมดูล re การใช้งาน regular expressions นั้นแพร่หลาย แต่มักจะซับซ้อน ดังนั้นเมื่อคิดจะใช้ regex สำหรับงานบางอย่าง ให้พิจารณาทางเลือกอื่นก่อน แล้วใช้ regex เป็นตัวเลือกสุดท้าย

ตัวอย่างหนึ่งของ regex คือ r"^(From|To|Cc).*?python-list@python.org" ต่อไปนี้เป็นคำอธิบาย: เครื่องหมาย ^ จับคู่ข้อความที่จุดเริ่มต้นของบรรทัด กลุ่มต่อไป (From|To|Cc) หมายถึงว่าบรรทัดต้องเริ่มด้วยหนึ่งในคำที่แยกด้วยเครื่องหมาย pipe | ซึ่งเรียกว่าโอเปอเรเตอร์ OR และ regex จะจับคู่ถ้าบรรทัดเริ่มด้วยคำใด ๆ ในกลุ่มนั้น .*? หมายถึงการจับคู่ตัวอักษรใด ๆ ยกเว้นตัวอักษร newline \n แบบไม่ตะกละ ส่วนแบบไม่ตะกละนั้นหมายถึงการจับคู่จำนวนครั้งให้น้อยที่สุด ตัวอักษร . หมายถึงตัวอักษรใด ๆ ที่ไม่ใช่ newline * หมายถึงการทำซ้ำ 0 ครั้งหรือมากกว่า และตัวอักษร ? ทำให้มันไม่ตะกละ

ดังนั้น บรรทัดต่อไปนี้จะถูกจับคู่ด้วย regex ดังกล่าว: From: python-list@python.org To: !asp]<,. python-list@python.org

การอ้างอิงทั้งหมดสำหรับไวยากรณ์ re มีอยู่ที่ python docs

ตัวอย่างของ regex ในการจับคู่ email ที่ "เหมาะสม" (เหมือนกับตัวอย่างในแบบฝึกหัด), ดูที่ this

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Previous Tutorial Next Tutorial Take the Test
Copyright © learnpython.org. Read our Terms of Use and Privacy Policy