繁体   English   中英

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

[英]match a list of words in a line using regex in python

我正在寻找一种表达式,以将字符串与["xxx", "yyy", "zzz"]类的单词列表进行匹配。 字符串需要包含所有三个单词,但是它们不必具有相同的顺序。

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

'"yyy" string of words and than “zzz" string of words “xxx"'

要么

'string of words “yyy””xxx””zzz” string of words'

简单的字符串操作:

mywords = ("xxx", "yyy", "zzz")
all(x in mystring for x in mywords)

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

import re
all(re.search(r"\b" + re.escape(word) + r"\b", mystring) for word in mywords)

我会all使用re.search查找匹配项。

>>> words = ('xxx', 'yyy' ,'zzz')
>>> text = "sdfjhgdsf zzz sdfkjsldjfds yyy dfgdfgfd xxx"
>>> all([re.search(w, text) for w in words])
True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM