ccf 201803-3 URL映射(python)
使用正则表达式
1 import re 2 import collections 3 n, m = list(map(int, input().split())) 4 arr = ['']*(m+n) 5 for i in range(n+m): 6 arr[i] = input() 7 8 def get_rule(rule): 9 result = "" 10 for test in re.findall(r"(/[^/]*)", rule): 11 if re.match(r"/<int>", test): 12 result += "/(\d+)" 13 elif re.match(r"/<str>", test): 14 result += "/(\w+)" 15 elif re.match(r"/<path>", test): 16 result += "/([\w/.]*)" 17 else: 18 result += test 19 return result + "$" 20 21 # 首先现将规则做成collection 22 rule_map = collections.OrderedDict() 23 for test in arr[0:n]: 24 rule_map[test.split(' ')[1]] = get_rule(test.split(' ')[0]) 25 26 # 将规则做成字典,每遇到一个路径,就跟所有规则比对 27 for test in arr[n:n+m]: # 遍历所有规则 28 for name, rule in rule_map.items(): 29 if re.match(rule, test): 30 print(name,end = " ") 31 # 注意如果是数字,需要去掉前导0,例09—>9 32 for i in re.match(rule, test).groups(): 33 print(int(i) if i.isdigit() else i,end = " ") 34 print() # 换行 35 break 36 else: 37 print("404")