Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Ruby中提取URI最后一段的最佳方法_Ruby_String_Uri_String Parsing - Fatal编程技术网

在Ruby中提取URI最后一段的最佳方法

在Ruby中提取URI最后一段的最佳方法,ruby,string,uri,string-parsing,Ruby,String,Uri,String Parsing,给定URI字符串,如: http://www.somesite.com/abc http://www.somesite.com/alpha/beta/abc http://www.somesite.com/alpha/abc 在Ruby中,在这些URI的末尾抓住abc最优雅的方式是什么 uri.split('/')[-1] 或 试试这些: if url =~ /\/(.+?)$/ last = $1 end 或 我会使用一个合适的URI解析器,比如其中一个,从URI获取路径。然后在/

给定URI字符串,如:

http://www.somesite.com/abc
http://www.somesite.com/alpha/beta/abc
http://www.somesite.com/alpha/abc
在Ruby中,在这些URI的末尾抓住
abc
最优雅的方式是什么

uri.split('/')[-1] 

试试这些:

if url =~ /\/(.+?)$/
  last = $1
end


我会使用一个合适的URI解析器,比如其中一个,从URI获取路径。然后在
/
处拆分它,并获得它的最后一部分:

require 'uri'

URI(uri).path.split('/').last

从终端命令行:

ruby -ruri -e "print File.basename(URI.parse('$URI').path)"
从.rb源代码内部:

require 'uri'
theURI = 'http://user:pass@example.com/foo/bar/baz/?lala=foo'
uriPathTail = File.basename(URI.parse(theURI).path) # => baz
无论你拥有什么合法的URI,它都能很好地工作


如果不使用URI.parse(),url的任何参数都将被错误地视为URI的最后一段。

虽然这里的答案中建议的
split
的所有用法都是合法的,但在我看来,它的代码更清晰:

last = File.basename(url)

如果该值是任意轨道字符串+URI,那么下面的解决方案应该可以工作

首先,从字符串中提取URI:

uri_string = URI.extract("Test 123 http://www.somesite.com/abc")
上面的命令返回一个数组

然后使用

uri_string[0].split('/').last

先决条件:需要将“uri”添加到ruby脚本中

@oldergod:
http://example.com/where?is=pancakes/house%3F
@muistooshort你会怎么做?从第一个
之前的最后一个
/
?@oldergod-See.@oldergod:是的,看Gumbo的答案。@oldergod那么你得到了什么呢?@muistooshort你可以使用
path.chomp('/')
在拆分之前删除它们。
uri_string = URI.extract("Test 123 http://www.somesite.com/abc")
uri_string[0].split('/').last