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)
這打?。?/p>
\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因此...的語法
希望能幫助到你!
添加回答
舉報