Parsing URL string in Ruby

14,897

Solution 1

I think the best solution would be to use the URI module. (You can do things like URI.parse('your_uri_string').query to get the part to the right of the ?.) See http://www.ruby-doc.org/stdlib/libdoc/uri/rdoc/

Example:

002:0> require 'uri' # or even 'net/http'
true
003:0> URI
URI
004:0> URI.parse('/xyz/mov/exdaf/daeed.mov?arg1=bla&arg2=asdf')
#<URI::Generic:0xb7c0a190 URL:/xyz/mov/exdaf/daeed.mov?arg1=bla&arg2=asdf>
005:0> URI.parse('/xyz/mov/exdaf/daeed.mov?arg1=bla&arg2=asdf').query
"arg1=bla&arg2=asdf"
006:0> URI.parse('/xyz/mov/exdaf/daeed.mov?arg1=bla&arg2=asdf').path
"/xyz/mov/exdaf/daeed.mov"

Otherwise, you can capture on a regex: /^(.*?)\?(.*?)$/. Then $1 and $2 are what you want. (URI makes more sense in this case though.)

Solution 2

Split the initial string on question marks.

str.split("?")
=> ["/xyz/mov/exdaf/daeed.mov", "arg1=blabla&arg2=3bla3bla"]

Solution 3

This seems to be what youre looking for, strings built-in split function:

"abc?def".split("?") => ["abc", "def"]

Edit: Bah, to slow ;)

Share:
14,897
Admin
Author by

Admin

Updated on June 27, 2022

Comments

  • Admin
    Admin almost 2 years

    I have a pretty simple string I want to parse in ruby and trying to find the most elegant solution. The string is of format /xyz/mov/exdaf/daeed.mov?arg1=blabla&arg2=3bla3bla

    What I would like to have is : string1: /xyz/mov/exdaf/daeed.mov string2: arg1=blabla&arg2=3bla3bla

    so basically tokenise on ?

    but can't find a good example. Any help would be appreciated.

  • glenn jackman
    glenn jackman over 14 years
    You could just require 'uri' instead of 'net/http'
  • Benjamin Oakes
    Benjamin Oakes over 14 years
    Good point; I always forget about that because I usually download something right after I parse a URI.
  • Benjamin Oakes
    Benjamin Oakes almost 12 years
    There's already a URL parsing library that would probably be a better choice if the input is always a URL.