开发者

How to return file path without url link?

I have

http://foobar.s3.amazonaws.com/uploads/users/15/photos/12/foo.jpg

How do I return

upload开发者_StackOverflows/users/15/photos/12/foo.jpg


It is better to use the URI parsing that is part of the Ruby standard library than to experiment with some regular expression that may or may not take every possible special case into account.

require 'uri'

url = "http://foo.s3.amazonaws.com/uploads/users/15/photos/12/foo.jpg"

path = URI.parse(url).path  
# => "/uploads/users/15/photos/12/foo.jpg"

path[1..-1]
# => "uploads/users/15/photos/12/foo.jpg"

No need to reinvent the wheel.


"http://foobar.s3.amazonaws.com/uploads/users/15/photos/12/foo.jpg".sub("http://foobar.s3.amazonaws.com/","")

would be an explicit version, in which you substitute the homepage-part with an empty string.

For a more universal approach I would recommend a regular expression, similar to this one:

string = "http://foobar.s3.amazonaws.com/uploads/users/15/photos/12/foo.jpg"
string.sub(/(http:\/\/)*.*?\.\w{2,3}\//,"")

If it's needed, I could explain the regular expression.


link = "http://foobar.s3.amazonaws.com/uploads/users/15/photos/12/foo.jpg"
path = link.match /\/\/[^\/]*\/(.*)/
path[1]
#=> "uploads/users/15/photos/12/foo.jpg"


Someone recommended this approach as well:

URI.parse(URI.escape('http://foobar.s3.amazonaws.com/uploads/users/15/photos/12/foo.jpg')).path[1..-1]

Are there any disadvantages using something like this versus a regexp approach?


The cheap answer is to just strip everything before the first single /.

Better answers are "How do I process a URL in ruby to extract the component parts (scheme, username, password, host, etc)?" and "Remove subdomain from string in ruby".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜