Regex có 2 thao tác: search và match.
- match(): Kiểm tra pattern chỉ ở đầu chuỗi, trả về match object nếu tìm thấy, ngược lại None.
- search(): Kiểm tra pattern bất kỳ đâu trong chuỗi, trả về match object nếu tìm thấy.
Ví dụ: chuỗi "Scientists dream about doing great things. Engineers Do them", tìm từ "Engineers".
Ví dụ match()
import re
pattern = "Engineers"
string = "Scientists dream about doing great things. Engineers Do them"
result = re.match(pattern, string)
if result:
print("Found")
else:
print("Not Found")Kết quả
Not Found
match() chỉ kiểm tra đầu chuỗi, "Engineers" không ở đầu -> Not Found.
Ví dụ search()
import re
pattern = "Engineers"
string = "Scientists dream about doing great things. Engineers Do them"
result = re.search(pattern, string)
if result:
print("Found")
else:
print("Not Found")Kết quả
Found
search() quét toàn chuỗi, tìm thấy "Engineers" -> Found.