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

Regex Python match nhiều từ ở bất kỳ vị trí

Dùng Python regex match nhiều từ trong string cho trước.

Ví dụ

import re

s = "These are roses and lilies and orchids, but not marigolds or .."
r = re.compile(r'\broses\b|\bmarigolds\b|\borchids\b', flags=re.I | re.X)
print(r.findall(s))

Kết quả

['roses', 'orchids', 'marigolds']

Giải thích pattern

  • \b: word boundary (ranh giới từ)
  • |: OR
  • re.I: case-insensitive
  • re.X: verbose mode (cho phép space/comment trong pattern)

Cách khác: dùng list join

words = ['roses', 'marigolds', 'orchids']
pattern = r'\b(?:' + '|'.join(map(re.escape, words)) + r')\b'
r = re.compile(pattern, re.I)
print(r.findall(s))