3 回答
TA贡献1811条经验 获得超6个赞
更新前的问题:
根据我的评论,我认为您使用了错误的方法。对我来说,您似乎可以简单地使用in:
words = ['cat', 'caterpillar', 'monkey', 'monk', 'doggy', 'doggo', 'dog']
if 'cat' in words:
print("yes")
else:
print("no")
回报:yes
words = ['cats', 'caterpillar', 'monkey', 'monk', 'doggy', 'doggo', 'dog']
if 'cat' in words:
print("yes")
else:
print("no")
回报:no
更新问题后:
现在,如果您的示例数据实际上并未反映您的需求,但您有兴趣在列表元素中查找子字符串,您可以尝试:
import re
words = ['MX_QW-765', 'RUC_PO-345', 'RUC_POLO-209']
srch = 'PO'
r = re.compile(fr'(?<=_){srch}(?=-)')
print(list(filter(r.findall, words)))
或使用match:
import re
words = ['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 re
words = ['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 re
words = ['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 字符串,您也可以将变量连接到模式中。
TA贡献1805条经验 获得超9个赞
尝试使用列表中的搜索词构建正则表达式替换:
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']
您可以清楚地看到我们为查找所有匹配关键字而构建的正则表达式替换。
TA贡献1853条经验 获得超6个赞
图案:
‘_PO[^\w]’
应该使用 re.search() 或 re.findall() 调用;它不适用于 re.match 因为它不考虑字符串开头的字符。
该模式为:匹配1 个下划线('_') 后跟1 个大写 P ('P')后跟 1 个大写 O ('O') 后跟一个不是单词字符的字符。特殊字符 '\w' 匹配[a-zA-Z0-9_].
‘_PO\W’
^ 这也可以用作建议的第一个模式的较短版本(在评论中注明@JvdV)
‘_PO[^A-Za-z]’
此模式使用“字符集而不是字母字符”。如果破折号干扰前两种模式中的任何一种。
要使用它来识别列表中的模式,您可以使用循环:
import re
For thing in my_list:
if re.search(‘_PO[^\w]’, thing) is not None:
# do something
print(thing)
这将使用re.search调用将模式匹配为条件中的 Trueif条件。当 re 不匹配一个字符串时,它返回 None;if re.search() is not None因此...的语法
希望能帮助到你!
添加回答
举报
