杨魅力
更新前的问题:根据我的评论,我认为您使用了错误的方法。对我来说,您似乎可以简单地使用in:words = ['cat', 'caterpillar', 'monkey', 'monk', 'doggy', 'doggo', 'dog']if 'cat' in words: print("yes")else: print("no")回报:yeswords = ['cats', 'caterpillar', 'monkey', 'monk', 'doggy', 'doggo', 'dog']if 'cat' in words: print("yes")else: print("no")回报:no更新问题后:现在,如果您的示例数据实际上并未反映您的需求,但您有兴趣在列表元素中查找子字符串,您可以尝试:import rewords = ['MX_QW-765', 'RUC_PO-345', 'RUC_POLO-209']srch = 'PO'r = re.compile(fr'(?<=_){srch}(?=-)')print(list(filter(r.findall, words)))或使用match:import rewords = ['MX_QW-765', 'RUC_PO-345', 'RUC_POLO-209']srch = 'PO'r = re.compile(fr'^.*(?<=_){srch}(?=-).*$')print(list(filter(r.match, words)))['RUC_PO-345']这将返回遵循模式的项目列表(在本例中为 )。我使用上面的常规模式来确保您的搜索值不会在搜索字符串的开头,而是在下划线之后,然后是-.现在,如果您有想要查找的产品列表,请考虑以下内容:import rewords = ['MX_QW-765', 'RUC_PO-345', 'RUC_POLO-209']srch = ['PO', 'QW']r = re.compile(fr'(?<=_)({"|".join(srch)})(?=-)')print(list(filter(r.findall, words)))或再次使用match:import rewords = ['MX_QW-765', 'RUC_PO-345', 'RUC_POLO-209']srch = ['PO', 'QW']r = re.compile(fr'^.*(?<=_)({"|".join(srch)})(?=-).*$')print(list(filter(r.match, words)))两者都会返回:['MX_QW-765', 'RUC_PO-345']请注意,如果您不支持 f 字符串,您也可以将变量连接到模式中。
Cats萌萌
尝试使用列表中的搜索词构建正则表达式替换:words = ['cat', 'caterpillar', 'monkey', 'monk', 'doggy', 'doggo', 'dog']your_text = 'I like cat, dog, rabbit, antelope, and monkey, but not giraffes'regex = r'\b(?:' + '|'.join(words) + r')\b'print(regex)matches = re.findall(regex, your_text)print(matches)这打印:\b(?:cat|caterpillar|monkey|monk|doggy|doggo|dog)\b['cat', 'dog', 'monkey']您可以清楚地看到我们为查找所有匹配关键字而构建的正则表达式替换。