如何从以下网址获取id = 123?
"http://www.test.com/user/controller/123/edit?query1='A'"
"http://www.test.com/user/controller/action_name?query1='A'&query2=123"
"http://www.test.com/user/controller/action_name?query2=123&query_3='B'"
"http://www.test.com/user/controller/123/edit"
答案 0 :(得分:2)
def q2id(url)
url[%r{controller/(\d+)},1] or url[%r{query2=(\d+)},1]
end
%w[
http://www.test.com/user/controller/123/edit?query1='A'
http://www.test.com/user/controller/action_name?query1='A'&query2=123
http://www.test.com/user/controller/action_name?query2=123&query_3='B'
http://www.test.com/user/controller/123/edit
].each{ |url| puts q2id(url) }
#=> 123
#=> 123
#=> 123
#=> 123
或更短但更不清晰:
def q2id(url)
url[%r{(?:controller/|query2=)(\d+)},1]
end