[ACCEPTED]-Wildcard string matching in Ruby-string-matching

Accepted answer
Score: 16

I don't see why you think it would be inefficient. Predictions 9 about these sorts of things are notoriously 8 unreliable, you should decide that it is 7 too slow before you go bending over backwards 6 to find a faster way. And then you should 5 profile it to make sure that this is where 4 the problem lies (btw there is an average 3 of 3-4x speed boost from switching to 1.9)

Anyway, it 2 should be pretty easy to do this, something 1 like:

class Globber 
  def self.parse_to_regex(str)
    escaped = Regexp.escape(str).gsub('\*','.*?')
    Regexp.new "^#{escaped}$", Regexp::IGNORECASE
  end

  def initialize(str)
    @regex = self.class.parse_to_regex str
  end

  def =~(str)
    !!(str =~ @regex)
  end
end


glob_strs = {
  '*hn'    => [['john', true, ], ['johnny', false,], ['hanna', false]],
  '*hn*'   => [['john', true, ], ['johnny', true, ], ['hanna', false]],
  'hn'     => [['john', false,], ['johnny', false,], ['hanna', false]],
  '*h*n*'  => [['john', true, ], ['johnny', true, ], ['hanna', true ]],
}

puts glob_strs.all? { |to_glob, examples|
  examples.all? do |to_match, expectation|
    result = Globber.new(to_glob) =~ to_match
    result == expectation
  end
}
# >> true
Score: 1
def create_regex(pattern)
 if pattern[0,1] != '*'
    pattern = '[^\w\^]' + pattern
 end
 if pattern[-1,1] != '*'
    pattern = pattern + '[^\w$]'
 end
 return Regexp.new( pattern.gsub(/\*/, '.*?') )
end

This methoid should return your regexp

PS: it 1 is not tested :D

More Related questions