在 Python 中使用 Regex 提取准确的单词或字符集

假设我有一个这样的列表。

List = ['MX_QW-765', 'RUC_PO-345', 'RUC_POLO-209'].

我想搜索并返回“PO”所在的匹配项。从技术上讲,我应该将其RUC_PO-345作为我的输出,但甚至RUC_POLO-209RUC_PO-345.


侃侃无极
浏览 212回答 3
3回答

杨魅力

更新前的问题:根据我的评论,我认为您使用了错误的方法。对我来说,您似乎可以简单地使用in:words = ['cat', 'caterpillar', 'monkey', 'monk', 'doggy', 'doggo', 'dog']if 'cat' in words:&nbsp; &nbsp; print("yes")else:&nbsp; &nbsp; print("no")回报:yeswords = ['cats', 'caterpillar', 'monkey', 'monk', 'doggy', 'doggo', 'dog']if 'cat' in words:&nbsp; &nbsp; print("yes")else:&nbsp; &nbsp; 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']您可以清楚地看到我们为查找所有匹配关键字而构建的正则表达式替换。

墨色风雨

图案:‘_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 reFor thing in my_list:&nbsp; &nbsp; if re.search(‘_PO[^\w]’, thing) is not None:&nbsp; &nbsp; &nbsp; &nbsp; # do something&nbsp; &nbsp; &nbsp; &nbsp; print(thing)这将使用re.search调用将模式匹配为条件中的 Trueif条件。当 re 不匹配一个字符串时,它返回 None;if re.search() is not None因此...的语法希望能帮助到你!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python