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

อธิบาย Python Regular Expression: search vs match

re.match() และ re.search() เป็นเมธอดของโมดูล re ใน Python

re.match() หาจับคู่ได้ก็ต่อเมื่อเกิดขึ้นที่ ต้นสตริง ตัวอย่าง เรียก match() บนสตริง 'TP Tutorials Point TP' หา pattern 'TP' จะจับคู่ได้

ตัวอย่าง

result = re.match(r'TP', 'TP Tutorials Point TP')
print(result.group(0))

ผลลัพธ์

TP

re.search() คล้าย match() แต่ ไม่จำกัดให้หาเฉพาะต้นสตริง หาได้จากตำแหน่งไหนก็ตาม

ตัวอย่าง

result = re.search(r'Tutorials', 'TP Tutorials Point TP')
print(result.group(0))

ผลลัพธ์

Tutorials

เห็นว่า search() หา pattern ได้จากตำแหน่งไหนก็ตามในสตริง