NullVoxPopuli
NullVoxPopuli

Reputation: 65183

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

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.

Upvotes: 0

Views: 2197

Answers (4)

giraff
giraff

Reputation: 4711

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

Upvotes: 10

zaarg
zaarg

Reputation: 21

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

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

Upvotes: 2

giraff
giraff

Reputation: 4711

How about:

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

Upvotes: 3

Dev Sahoo
Dev Sahoo

Reputation: 12101

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

Upvotes: 2

Related Questions