module NickPattern
NickPattern — mIRC-style wildcard matching for IRC nicks (*, ?, […]). Public: pattern?, match? Tests: test/lib/nick_pattern_test.rb
Public Instance Methods
Source
# File lib/nick_pattern.rb, line 98 def escape_char_class(chars) chars.chars.map do |c| case c when "\\", "]", "-", "^" "\\#{c}" else Regexp.escape(c) end end.join end
Source
# File lib/nick_pattern.rb, line 14 def match?(nick, entry) nick = nick.to_s entry = entry.to_s return nick.casecmp?(entry) unless pattern?(entry) re = to_regexp(entry) return false unless re !!(nick =~ re) end
Source
# File lib/nick_pattern.rb, line 57 def parse_char_class(pattern, start_idx) return nil unless pattern[start_idx] == "[" i = start_idx + 1 return nil if i >= pattern.length negated = false if pattern[i] == "!" || pattern[i] == "^" negated = true i += 1 end return nil if i >= pattern.length chars = +"" until pattern[i] == "]" return nil if i >= pattern.length if i + 2 < pattern.length && pattern[i + 1] == "-" && pattern[i + 2] != "]" from = pattern[i] to = pattern[i + 2] return nil if from.ord > to.ord (from.ord..to.ord).each { |cp| chars << cp.chr(Encoding::UTF_8) } i += 3 else chars << pattern[i] i += 1 end end i += 1 body = if negated "[^#{escape_char_class(chars)}]" else "[#{escape_char_class(chars)}]" end { body: body, consumed: i - start_idx } end
Source
# File lib/nick_pattern.rb, line 10 def pattern?(entry) entry.to_s.match?(/[\*\?\[]/) end
Source
# File lib/nick_pattern.rb, line 25 def to_regexp(pattern) i = 0 len = pattern.length re = +"\\A" while i < len char = pattern[i] case char when "*" re << ".*" i += 1 when "?" re << "." i += 1 when "[" parsed = parse_char_class(pattern, i) return nil unless parsed re << parsed[:body] i += parsed[:consumed] else re << Regexp.escape(char) i += 1 end end re << "\\z" Regexp.new(re, Regexp::IGNORECASE) rescue RegexpError nil end