Method: FatCore::String#fuzzy_match

Defined in:
lib/fat_core/string.rb

#fuzzy_match(matcher) ⇒ String?

Return the matched portion of self, minus punctuation characters, if self matches the string matcher using the following notion of matching:

  1. Remove all periods, commas, apostrophes, and asterisks (the punctuation characters) from both self and matcher,
  2. Treat ':' in the matcher as the equivalent of '.*' in a regular expression, that is, match anything in self,
  3. Ignore case in the match
  4. Match if any part of self matches matcher

Examples:

"St. Luke's Hospital".fuzzy_match('st lukes') #=> 'St Lukes'
"St. Luke's Hospital".fuzzy_match('luk:hosp') #=> 'Lukes Hosp'
"St. Luke's Hospital".fuzzy_match('st:spital') #=> 'St Lukes Hospital'
"St. Luke's Hospital".fuzzy_match('st:laks') #=> nil

Parameters:

  • matcher (String)

    pattern to test against where ':' is wildcard

Returns:

  • (String)

    the unpunctuated part of self that matched

  • (nil)

    if self did not match matcher

[View source]

260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/fat_core/string.rb', line 260

def fuzzy_match(matcher)
  # Remove periods, asterisks, commas, and apostrophes
  matcher = matcher.gsub(/[\*.,']/, '')
  target = gsub(/[\*.,']/, '')
  matchers = matcher.split(/[: ]+/)
  regexp_string = matchers.map { |m| ".*?#{Regexp.escape(m)}.*?" }.join('[: ]')
  regexp_string.sub!(/^\.\*\?/, '')
  regexp_string.sub!(/\.\*\?$/, '')
  regexp = /#{regexp_string}/i
  matched_text =
    if (match = regexp.match(target))
      match[0]
    end
  matched_text
end