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

Khớp từ nguyên vẹn (whole word) trong regex Python

Để khớp từ hoàn chỉnh (không phải một phần của từ dài hơn), dùng lookaround kiểm tra ranh giới non-word.

Pattern

(?<=[\W_])word(?=[\W_])
  • (?<=[\W_]) — positive lookbehind: trước từ phải là non-word hoặc underscore.
  • (?=[\W_]) — positive lookahead: sau từ phải là non-word hoặc underscore.

Ví dụ

import re
s = "https://www.google.com/meeting_agenda_minutes.html"
result = re.findall(r'(?<=[\W_])meeting(?=[\W_])', s)
print(result)  # ['meeting']

Thay thế đơn giản hơn (Python 3.7+): Dùng \b word boundary:

re.findall(r'\bmeeting\b', s)  # ['meeting']

\b khớp vị trí giữa \w và \W (hoặc đầu/cuối chuỗi).