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

วิธีเขียน Regex จับคำหลายคำที่ไหนก็ได้ใน Python

โค้ดต่อไปนี้ใช้ Python Regex จับ Multiple Words ใน String ที่กำหนด

ตัวอย่าง

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))

ผลลัพธ์

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

re.I = Case-insensitive re.X = Verbose mode (อ่านง่าย) \b = Word boundary