2010-11-06 98 views
29

新的紅寶石,我將如何得到像URL文件擴展名:如何從url獲取文件擴展名?

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

另外,我怎麼會格式化該字符串,在C#中我會做:

string.format("http://www.example.com/{0}.{1}", filename, extension); 
+3

我強烈建議使用URI或Addressable/URI庫。儘管您可以使用格式化將值直接注入到URL中,但這些庫提供了很多很好的功能,可以將URL拆分爲組件,重建它,並確保url的結構正確。 – 2010-11-06 15:51:13

回答

61

使用File.extname

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

格式字符串

"http://www.example.com/%s.%s" % [filename, extension] 
+0

所以如果返回值是「」,我將如何檢查在if語句中的那個?如果extesion ==「」? – Blankman 2010-11-06 15:26:58

+1

'if extension.empty?' – 2010-11-06 16:16:23

+5

它出現'File.extname'不會剝離查詢字符串。所以如果你的網址是'http://www.example.com/download.mp3?hello = world',那麼它會返回'.mp3?hello = world'。只是要記住。 – 2013-01-21 21:43:43

3
url = 'http://www.example.com/asdf123.gif' 
extension = url.split('.').last 

將爲您獲取URL的擴展名(以最簡單的方式)。現在,對於輸出格式:

printf "http://www.example.com/%s.%s", filename, extension 
+0

這兩個解決方案都不處理查詢參數,因此您可能需要添加URI.parse對於第二部分,「http://www.example.com/#{filename}.#{extension}」將會執行 – Zaki 2010-11-06 15:12:52

+2

並且更精美的是' url.split('。')。last'和'「http://www.example.com/%s.%s」%[文件名,擴展名]'。 – 2010-11-06 15:13:01

+1

如果URL是「http://www.example.com/dir」,該怎麼辦? – 2010-11-06 15:17:51

2

你可以使用Ruby的URI class這樣得到的URI的片段(即文件的相對路徑),並在一個點最後出現分裂它(這也將工作,如果URL中包含查詢部分):

require 'uri' 
your_url = 'http://www.example.com/asdf123.gif' 
fragment = URI.split(your_url)[5] 

extension = fragment.match(/\.([\w+-]+)$/) 
+0

同樣,爲什麼只要調用'string.split()',正則表達式是必需的? – 2010-11-06 15:13:30

+0

您在評論時刪除了RegExp;) – AdrianoKF 2010-11-06 15:14:10

+0

用於像「http://www.example.com/asdf123.php?myparam=1234.435.24」之類的賭場。 – 2010-11-06 15:14:42

22

這對文件與查詢字符串

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

也返回「」如果文件沒有擴展

+0

但這將失敗:「http://recyclewearfashion.com」,或者,至少,給出錯誤的答案 – Itzik984 2017-09-03 15:22:56

+0

@ Itzik984有一個無效協議(缺少HTTP(S)),所以是不是一個有效的URI – Orlando 2017-09-04 19:52:23

+1

這對於「http:// recyclewearfashion.com」也會失敗:) – Itzik984 2017-09-05 08:09:13

0

我意識到這是一個古老的問題,但這裏的使用Addressable另一次投票。您可以使用.extname方法,該方法即使對查詢字符串也按需要工作:

Addressable::URI.parse('http://www.example.com/asdf123.gif').extname # => ".gif" 
Addressable::URI.parse('http://www.example.com/asdf123.gif?foo').extname # => ".gif"