在 Ruby 中解析 URL 字符串 [英] Parsing URL string in Ruby

查看:67
本文介绍了在 Ruby 中解析 URL 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的字符串,我想用 ruby​​ 解析并尝试找到最优雅的解决方案.字符串的格式/xyz/mov/exdaf/daeed.mov?arg1=blabla&arg2=3bla3bla

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

我想要的是:字符串 1:/xyz/mov/exdaf/daeed.movstring2: arg1=blabla&arg2=3bla3bla

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

所以基本上标记化?

但是找不到好的例子.任何帮助将不胜感激.

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

推荐答案

我认为最好的解决方案是使用 URI 模块.(您可以执行诸如 URI.parse('your_uri_string').query 之类的操作来获取 ? 右侧的部分.)请参阅 http://www.ruby-doc.org/stdlib/libdoc/uri/rdoc/

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/

示例:

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 在这种情况下更有意义.)

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

这篇关于在 Ruby 中解析 URL 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆