在python中使用正则表达式匹配一行中的单词列表

sha*_*ash 0 python

我正在寻找一个表达式来将字符串与诸如["xxx", "yyy", "zzz"]. 字符串需要包含所有三个单词,但它们的顺序不必相同。

例如,应匹配以下字符串:

'"yyy" string of words and than “zzz" string of words “xxx"'
Run Code Online (Sandbox Code Playgroud)

或者

'string of words “yyy””xxx””zzz” string of words'
Run Code Online (Sandbox Code Playgroud)

Tim*_*ker 5

简单的字符串操作:

mywords = ("xxx", "yyy", "zzz")
all(x in mystring for x in mywords)
Run Code Online (Sandbox Code Playgroud)

如果单词边界相关(即您想匹配zzz但不匹配Ozzzy):

import re
all(re.search(r"\b" + re.escape(word) + r"\b", mystring) for word in mywords)
Run Code Online (Sandbox Code Playgroud)