解决方案
这里没有魔法,所以必须对每一对进行迭代:import re
collections = {}
collections[re.compile('n.*')] = 'word that starts with n'
collections[re.compile(r'\b....\b')] = '4 letter word'
def find_matching_regexen(word, dicts=collections):
return [description for regex, description in dicts.items() if regex.match(word)]
print(find_matching_regexen('never'))
# ['word that starts with n']
print(find_matching_regexen('boat'))
# ['4 letter word']
print(find_matching_regexen('nice'))
# ['word that starts with n', '4 letter word']
print(find_matching_regexen('dog'))
# []
如果输出顺序很重要,则必须使用^{}
注意Explicit is better than implicit.
如果你想用Python实现某件事,通常必须编写它。语法可能简短明了,但仍然需要明确地写出来。在
所以不,字符串不会被认为与dict中匹配的regex具有相同的哈希
如果你在寻找更多的魔力,你可以看看Ruby。它对patterns有更广泛的定义,可以是类、正则表达式或字符串:
^{pr2}$
模式也用于case语句中。例如,可以将字符串与正则表达式匹配,而无需转换或显式方法调用:def find_matching_regexen(word)
case word
when /^n.*/
"Word that starts with n"
when /\b....\b/
"4 letter word"
end
end
puts find_matching_regexen("boat")
# "4 letter word"
puts find_matching_regexen("nice")
# "Word that starts with n"
puts find_matching_regexen("dog")
# nil