How to get the file extension from a url?

后端 未结 5 943
小蘑菇
小蘑菇 2021-02-03 20:02

New to ruby, how would I get the file extension from a url like:

http://www.example.com/asdf123.gif

Also, how would I format this string, in c#

相关标签:
5条回答
  • 2021-02-03 20:05

    Use File.extname

    File.extname("test.rb")         #=> ".rb"
    File.extname("a/b/d/test.rb")   #=> ".rb"
    File.extname("test")            #=> ""
    File.extname(".profile")        #=> ""
    

    To format the string

    "http://www.example.com/%s.%s" % [filename, extension]
    
    0 讨论(0)
  • 2021-02-03 20:05

    I realize this is an ancient question, but here's another vote for using Addressable. You can use the .extname method, which works as desired even with a query string:

     Addressable::URI.parse('http://www.example.com/asdf123.gif').extname # => ".gif"
     Addressable::URI.parse('http://www.example.com/asdf123.gif?foo').extname # => ".gif"
    
    0 讨论(0)
  • 2021-02-03 20:22
    url = 'http://www.example.com/asdf123.gif'
    extension = url.split('.').last
    

    Will get you the extension for a URL(in the most simple manner possible). Now, for output formatting:

    printf "http://www.example.com/%s.%s", filename, extension
    
    0 讨论(0)
  • 2021-02-03 20:27

    You could use Ruby's URI class like this to get the fragment of the URI (i.e. the relative path of the file) and split it at the last occurrence of a dot (this will also work if the URL contains a query part):

    require 'uri'
    your_url = 'http://www.example.com/asdf123.gif'
    fragment = URI.split(your_url)[5]
    
    extension = fragment.match(/\.([\w+-]+)$/)
    
    0 讨论(0)
  • 2021-02-03 20:30

    This works for files with query string

    file = 'http://recyclewearfashion.com/stylesheets/page_css/page_css_4f308c6b1c83bb62e600001d.css?1343074150'
    File.extname(URI.parse(file).path) # => '.css'
    

    also returns "" if file has no extension

    0 讨论(0)
提交回复
热议问题