Ruby: How do I capture part of a string with regex?
I have
file_开发者_如何学Cext = attach.document_file_name.capture(/\.[^.]*$/)
but i guess there is no method capture.
I'm trying to get the file extension from a string. I don't yet have the file.
There is also the built-in ruby function File.extname:
file_ext = File.extname(attach.document_file_name)
(with the difference that File.extname('hello.')
returns ''
, whereas your regex would return '.'
)
How about:
file_ext = attach.document_file_name[/\.[^.]*$/]
You can do RegEx match in ruby like so:
file_ext = (/\.[^.]*$/.match(attach.document_file_name.to_s)).to_s
Fore more information please check http://ruby-doc.org/core/classes/Regexp.html
If you want to use an regexp to do this, you can simply do:
irb(main):040:0> "foo.txt"[/\w*.(\w*)/,1]
=> "txt"
精彩评论