1

I'm running Ruby 1.9.2p290 and Rails 3.1.0.rc5. When I run this regex it matches everything:

files = Dir.glob("#{File.dirname(video.path)}/*")
files.each do |f|
  File.delete(f) unless File.extname(f) =~ /[.flv|.gif]/
end

Am I missing something?

1
  • /[.flv|.gif]/ means "one character out of ., f, l, v, |, g or i". Commented Aug 7, 2011 at 7:41

2 Answers 2

5

To ensure that only the exact extension is matched, use

File.delete(f) unless File.extname(f) =~ /^\.(?:flv|gif)$/

Explanation:

^     # Start of string
\.    # Match .
(?:   # Match the following: Either...
 flv  # flv
|     # or
 gif  # gif
)     # End of alternation
$     # End of string
Sign up to request clarification or add additional context in comments.

Comments

3

I think you want to match either extension ".flv" or ".gif". Therefore you can use the following regex:

/^(\.flv|\.gif)$/

Your regex defines a matching character set ([...]) and this give true for extensions containing any of the characters 'f', 'g', 'i', 'l', 'v', '|', '.'. Since any file with an extension has a dot in the extension, this will match any file wit any extension.

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.