[英]Python: Elegant way to check if at least one regex in list matches a string
我在 python 中有一個正則表達式列表和一個字符串。 有沒有一種優雅的方法來檢查列表中的至少一個正則表達式是否與字符串匹配? 我所說的優雅,是指比簡單地遍歷所有正則表達式並根據字符串檢查它們並在找到匹配項時停止更好的東西。
基本上,我有這段代碼:
list = ['something','another','thing','hello']
string = 'hi'
if string in list:
pass # do something
else:
pass # do something else
現在我想在列表中有一些正則表達式,而不僅僅是字符串,我想知道是否有一個優雅的解決方案來檢查匹配以替換if string in list:
。
import re
regexes = [
# your regexes here
re.compile('hi'),
# re.compile(...),
# re.compile(...),
# re.compile(...),
]
mystring = 'hi'
if any(regex.match(mystring) for regex in regexes):
print 'Some regex matched!'
import re
regexes = [
"foo.*",
"bar.*",
"qu*x"
]
# Make a regex that matches if any of our regexes match.
combined = "(" + ")|(".join(regexes) + ")"
if re.match(combined, mystring):
print "Some regex matched!"
Ned和Nosklo的答案混合在一起。 保證任何長度的列表...希望你喜歡
import re
raw_lst = ["foo.*",
"bar.*",
"(Spam.{0,3}){1,3}"]
reg_lst = []
for raw_regex in raw_lst:
reg_lst.append(re.compile(raw_regex))
mystring = "Spam, Spam, Spam!"
if any(compiled_reg.match(mystring) for compiled_reg in reg_lst):
print("something matched")
以下是我根據其他答案選擇的內容:
raw_list = ["some_regex","some_regex","some_regex","some_regex"]
reg_list = map(re.compile, raw_list)
mystring = "some_string"
if any(regex.match(mystring) for regex in reg_list):
print("matched")
如果循環遍歷字符串,則時間復雜度為O(n)。 更好的方法是將這些正則表達式組合為正則表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.