题意:
给出几条规则和url,判断每条url是否有匹配规则,有就输出规则名字和匹配参数。
这题题目说的不够细,url后面有‘/’的只能和后面也有‘/’的规则匹配。例如url:/abc/def/ 和 规则:/abc/def 是不能匹配的。然后后面没有‘/’的url只能和后面没有‘/’的规则匹配(path与有结束的url匹配)。以前不懂,现在才想到这个地方,修改下代码就终于100了。
python代码:
# 匹配url和规则
def match(url, rule, args):
while url and rule:
u, r = url.pop(0), rule.pop(0)
if r == '<int>' and u.isdigit():
args.append(u)
elif r == '<str>' and not u.isdigit() and u: # 如果该规则项是str,且该url项非空非数字
args.append(u)
elif r == '<path>' and url[-1]:
path = [u]
while url:
path.append(url.pop(0))
args.append('/'.join(path))
elif u == r:
continue
else:
return False
return False if url or rule else True
n, m = map(int, input().split())
rules = []
for i in range(n):
rules.append(input().split())
for i in range(m):
url = input().split('/')[1:] # 处理url,如果结尾有‘/’,列表最后一项是空字符串。
for rule, name in rules:
rule = rule.split('/')[1:] # 处理规则,同上理
args = [] # 匹配参数
# 判断是否匹配这条规则,匹配就打印
if match(url[:], rule[:], args):
print(name, end=' ')
[print(int(e) if e.isdigit() else e, end=' ') for e in args]
print()
break
# 所有规则都不匹配就404
else:
print('404')
# 5 4
# /articles/2003/ special_case_2003
# /articles/<int>/ year_archive
# /articles/<int>/<int>/ month_archive
# /articles/<int>/<int>/<str>/ article_detail
# /static/<path> static_serve
# /articles/2004/
# /articles/1985/09/aloha/
# /articles/hello/
# /static/js/jquery.js
#