From: "lrlebron@..." Date: 2007-09-02T04:30:05+09:00 Subject: Re: Parsing query parameters from hyperlink On Sep 1, 2:15 pm, Aaron Patterson wrote: > On Sun, Sep 02, 2007 at 04:00:20AM +0900, Robert Klemme wrote: > > On 01.09.2007 19:34, lrleb...@gmail.com wrote: > > >I am trying to parse strings like this > > > > > > >I need to get the cpnum value (555) > > > >I am using the following function > > > >def get_drugId(link) > > > arrParts = link.html.split('?') > > > cpnum = arrParts[1].split('&') > > > cpnumparts= cpnum[0].split("=") > > > drugId = cpnumparts[1] > > > end > > > >but I imagine there is a simpler way to do this. Also, I would like > > >something more flexible that would return all the query parameters (if > > >there are more than one) in an array or a hash. > > > >Any ideas? > > > The std lib: > > > require 'uri' > > > irb(main):006:0> u=URI.parse("http://foo/bar?dodo=1&dada=2") > > => # > > irb(main):007:0> u.query > > => "dodo=1&dada=2" > > irb(main):008:0> u.query.split('&') > > => ["dodo=1", "dada=2"] > > ... > > Query strings are allowed to use semicolons as delimeters, not to > mention you must handle multiple values per key. I recommend using the > CGI library with the URI library: > > irb(main):001:0> require 'uri' > => true > irb(main):002:0> require 'cgi' > => true > irb(main):003:0> CGI.parse(URI.parse('http://foo/?a=b&b=c').query) > => {"a"=>["b"], "b"=>["c"]} > irb(main):004:0> CGI.parse(URI.parse('http://foo/?a=b;b=c').query) > => {"a"=>["b"], "b"=>["c"]} > irb(main):005:0> CGI.parse(URI.parse('http://foo/?b=a;b=c').query) > => {"b"=>["a", "c"]} > irb(main):006:0> > > -- > Aaron Pattersonhttp://tenderlovemaking.com/- Hide quoted text - > > - Show quoted text - This would work if the string where a proper url. But it is a hyperlink.