是否可以实现一个以键为正则表达式、 Action (带参数)为值的字典?
例如
key = "actionname 1 2", value = "method(1, 2)"
key = "differentaction par1 par2", value = "appropriate_method(par1, par2)"
用户在键中键入,我需要使用作为用户输入的一部分提供的参数执行匹配方法。
如果我们能在 O(1)
时间内实现查找,那就太好了,即使它不可能至少我正在寻找解决这个问题的方法。
我将使用几百个正则表达式(例如 300
)和匹配的参数化操作来执行。
我可以编写一个循环来实现这一点,但是有什么优雅的方法可以不使用 for 循环来做到这一点吗?
相关问题:Hashtable/dictionary/map lookup with regular expressions
最佳答案
是的,这完全有可能:
import re
dict = {}
dict[re.compile('actionname (\d+) (\d+)')] = method
dict[re.compile('differentaction (\w+) (\w+)')] = appropriate_method
def execute_method_for(str):
#Match each regex on the string
matches = (
(regex.match(str), f) for regex, f in dict.iteritems()
)
#Filter out empty matches, and extract groups
matches = (
(match.groups(), f) for match, f in matches if match is not None
)
#Apply all the functions
for args, f in matches:
f(*args)
关于python - python中的正则表达式字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10931044/