Class: Utils::Patterns::FuzzyPattern

Inherits:
Pattern show all
Defined in:
lib/utils/patterns.rb

Overview

A fuzzy pattern matcher that performs partial string matching while preserving character order.

This class implements a pattern matching strategy that allows for flexible matching of strings where the characters of the search pattern appear in sequence within the target string, but not necessarily consecutively. It is particularly useful for finding text patterns with potential typos or when only partial information about the target is available.

Examples:

fuzzy_pattern = FuzzyPattern.new(pattern: 'abc')
fuzzy_pattern.match('a1b2c3') # => matches because 'a', 'b', and 'c' appear in order

Instance Attribute Summary

Attributes inherited from Pattern

#matcher

Instance Method Summary collapse

Methods inherited from Pattern

#method_missing

Constructor Details

#initialize(opts = {}) ⇒ FuzzyPattern

Initializes a fuzzy pattern matcher by processing the pattern string and compiling it into a regular expression.

This method takes the configured pattern string and converts it into a regular expression that can match strings in a fuzzy manner, allowing for partial matches while preserving the order of characters. It handles case sensitivity based on the configuration.

Parameters:

  • opts (Hash) (defaults to: {})

    a hash containing the pattern configuration options

Options Hash (opts):

  • :cset (String)

    the character set to filter pattern characters against

  • :icase (TrueClass, FalseClass)

    whether the pattern matching should be case sensitive

  • :pattern (String)

    the pattern string to be used for matching



89
90
91
92
93
94
95
96
97
# File 'lib/utils/patterns.rb', line 89

def initialize(opts = {})
  super
  r = @pattern.split(//).grep(/[[:print:]]/).map { |x|
    "(#{Regexp.quote(x)})"
  } * '.*?'
  @matcher = Regexp.new(
    "\\A(?:.*/.*?#{r}|.*#{r})", @icase ? Regexp::IGNORECASE : 0
  )
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Utils::Patterns::Pattern