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

ความแตกต่างระหว่าง re.match() re.search() และ re.findall() ใน Python

re.match(), re.search(), re.findall() เป็นเมธอดของโมดูล re

re.match()

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

ตัวอย่าง

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

ผลลัพธ์

TP

re.search()

คล้าย match() แต่ ไม่จำกัดต้นสตริง หาได้จากตำแหน่งไหนก็ตาม

ตัวอย่าง

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

ผลลัพธ์

Tutorials

re.findall()

ได้ list ของ pattern ที่จับคู่ทั้งหมด ค้นหาจากต้นหรือท้าย คืน occurrences ทั้งหมด แนะนำใช้เสมอ ทำงานคล้าย search() และ match()

ตัวอย่าง

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

ผลลัพธ์

TP