从不同形式的URL中提取参数

时间:2012-03-01 07:26:23

标签: ruby-on-rails ruby regex uri

如何从以下网址获取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"

1 个答案:

答案 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