开发者

Ruby: How do I capture part of a string with regex?

开发者 https://www.devze.com 2023-01-07 22:13 出处:网络
I have file_开发者_如何学Cext = attach.document_file_name.capture(/\\.[^.]*$/) but i guess there is no method capture.

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"
0

精彩评论

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