Morten
Morten

Reputation: 1869

Ruby Regex do not match

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?

Upvotes: 1

Views: 1641

Answers (2)

Howard
Howard

Reputation: 39217

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.

Upvotes: 3

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

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

Upvotes: 5

Related Questions