简体   繁体   English

在Ruby中解析URL字符串

[英]Parsing URL string in Ruby

I have a pretty simple string I want to parse in ruby and trying to find the most elegant solution. 我有一个非常简单的字符串,我想在ruby中解析并试图找到最优雅的解决方案。 The string is of format /xyz/mov/exdaf/daeed.mov?arg1=blabla&arg2=3bla3bla 该字符串的格式为/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 我想要的是: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. 任何帮助,将不胜感激。

Split the initial string on question marks. 在问号上拆分初始字符串。

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

I think the best solution would be to use the URI module. 我认为最好的解决方案是使用URI模块。 (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/ (您可以执行URI.parse('your_uri_string').query以获取?右侧的部分。)请参阅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. 那么$1$2就是你想要的。 ( URI makes more sense in this case though.) (但在这种情况下URI更有意义。)

This seems to be what youre looking for, strings built-in split function: 这似乎是你要找的,字符串内置拆分功能:

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

Edit : Bah, to slow ;) 编辑 :呸,慢;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM