Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การจับคู่ (Match) เทียบกับการค้นหา (Search) ใน Python

Python มีการดำเนินการพื้นฐานสองแบบที่อิงตามนิพจน์ปกติ: match ตรวจสอบการจับคู่เฉพาะที่ต้นทางของสตริง ในขณะที่ search ตรวจสอบการจับคู่ที่ใดก็ตามในสตริง (นี่คือค่าเริ่มต้นของ Perl)

ตัวอย่าง

#!/usr/bin/python
import re
line = "Cats are smarter than dogs"
matchObj = re.match(r'dogs', line, re.M|re.I)
if matchObj:
    print "match --> matchObj.group() : ", matchObj.group()
else:
    print "No match!!"
searchObj = re.search(r'dogs', line, re.M|re.I)
if searchObj:
    print "search --> searchObj.group() : ", searchObj.group()
else:
    print "Nothing found!!"

ผลลัพธ์ (Output)

เมื่อรันโค้ดข้างต้น จะได้ผลลัพธ์ดังนี้:

No match!!
search --> searchObj.group() : dogs