Parsing a URL string in Ruby

I have a pretty simple string that I want to parse in a ruby โ€‹โ€‹and try to find the most elegant solution. The string has the format /xyz/mov/exdaf/daeed.mov?arg1=blabla&arg2=3bla3bla

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

so basically tokenize?

but cannot find a good example. Any help would be appreciated.

+5
source share
3 answers

Divide the source line into question marks.

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

, URI. ( - URI.parse('your_uri_string').query, ?.) . http://www.ruby-doc.org/stdlib/libdoc/uri/rdoc/

:

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"

: /^(.*?)\?(.*?)$/. $1 $2 - , . (URI , .)

+10

This is similar to what you are looking for, lines of the built-in split function:

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

Edit : Ba to slow down;)

+6
source

All Articles