如何在Ruby 1.8中解析URI的查询部分?

时间:2011-07-30 02:18:47

标签: ruby parsing uri ruby-1.8

在Ruby 1.8中,使用URI标准库,我可以解析

http://au.easyroommate.com/content/common/listing_detail.aspx?code=H123456789012&from=L123456789012345

使用URI.split获取

["http", nil, "au.easyroommate.com", nil, nil,
"/content/common/listing_detail.aspx", nil, 
"code=H123456789012&from=L123456789012345", nil]

但是有可能在不使用我自己的hackery的情况下从查询部分获取H123456789012位(例如,按&拆分然后获取匹配/code.(.*)/的位吗?

2 个答案:

答案 0 :(得分:3)

您正在寻找 CGI::parse 方法

params = CGI::parse("query_string")
  # {"name1" => ["value1", "value2", ...],
  #  "name2" => ["value1", "value2", ...], ... }

答案 1 :(得分:3)

您可以使用Rack::Utils,其中有一个名为parse_nested_query的方法,您可以通过该网址传递查询字符串:

Rack::Utils.parse_nested_query(uri.query_string)

然后,这将返回表示查询字符串的Hash对象,允许您访问code