0

I have

  file_ext = 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.

1
  • There's no need to start all of your questions with "Ruby on Rails" or "Regex" - that's what tags are for. Commented Jul 20, 2010 at 17:50

4 Answers 4

10

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 '.')

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Why mess with regular expressions when there is a function that does exactly what you want
3

How about:

file_ext = attach.document_file_name[/\.[^.]*$/]

1 Comment

Note that it returns nil if no extension is found. If you prefer an empty string, append a to_s at the end of line.
2

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

Comments

2

If you want to use an regexp to do this, you can simply do:

irb(main):040:0> "foo.txt"[/\w*.(\w*)/,1]
=> "txt"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.