Friday, October 01, 2010

DOS wildcards to Ruby regexs

Ever needed to convert a DOS wildcard like "?WIN*.EXE" to a regex for evaluation? If so here's little Ruby code snippet:
class Regexp
   def self.from_wildcard(wildcard, options = '')
      /^#{wildcard.gsub(/[\.\*\?]/) { |m| { '.' => '\.', '*' => '.*', '?' => '.' }[m] }}$/#{options}
   end
end

Here's the usage and result:
puts Regexp::from_wildcard "?WIN*.EXE"

=> (?-mix:^.WIN.*\.EXE$)

"AWINNER.EXE".match(Regexp::from_wildcard "?win*.exe", 'i')

=> #(matchdata "AWINNER.EXE")

Have fun! ;)

Online Petition
Online Petition