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

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

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

ตัวอย่าง

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

ผลลัพธ์

Tutorials

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

ตัวอย่าง

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

ผลลัพธ์

TP