简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM