From: Rob Biedenharn Date: 2009-01-05T05:46:17+09:00 Subject: Re: Finding filename from a URL On Jan 4, 2009, at 1:04 PM, Robert Klemme wrote: > On 04.01.2009 17:29, Sam Fent wrote: >> This is just a basic parsing question, really. I'm trying to work out >> how I would process a URL such as >> "http://www.example.com/x/y/z/myfile.txt" and get back the filename >> "myfile". Basically the pattern is to get the past part of the string >> after the final /, and then strip off the filetype. > > IMHO it is not a good idea to use a File method for URL's because > File.basename has different criteria > > irb(main):003:0> File.basename 'http://test.com/aaa\\bbb.txt' > => "bbb.txt" > > Although I am not sure whether a backslash is allowed there, this is > what I'd do: > > irb(main):001:0> url = 'http://www.example.com/x/y/z/myfile.txt' > => "http://www.example.com/x/y/z/myfile.txt" > irb(main):002:0> name = url[%r{[^/]+\z}] > => "myfile.txt" > > Kind regards > > robert > Rather than jump to a Regexp, just use the right tool for the job. irb> require 'uri' => true irb> u=URI.parse 'http://www.example.com/x/y/z/myfile.txt' => # irb> u.path => "/x/y/z/myfile.txt" irb> File.basename u.path, '.txt' => "myfile" -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com