Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Hàm search() trong module re Python

re.search(pattern, string) quét chuỗi từ trái sang phải, trả về match object đầu tiên tìm thấy (hoặc None).

Cú pháp

re.search(pattern, string, flags=0)

Ví dụ

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

Match object methods

  • group() / group(0) — toàn bộ match.
  • group(1), group(2)... — capturing groups.
  • groups() — tuple tất cả groups.
  • start(), end(), span() — vị trí match.

So sánh nhanh

re.match(r'Tutorials', s)   # None (không ở đầu)
re.search(r'Tutorials', s)  # Match object (tìm thấy ở giữa)
re.findall(r'Tutorials', s) # ['Tutorials'] (tất cả)