Class: RegexGenerator::CharactersRecognizer

Inherits:
Object
  • Object
show all
Defined in:
lib/regex_generator/characters_recognizer.rb

Constant Summary collapse

PATTERNS =
[/[A-Z]/, /[a-z]/, /\d/, /\n/, /\s/, /./].freeze

Class Method Summary collapse

Class Method Details

.recognize(text, options = {}) ⇒ Array

Creates array with regex representation for each char from the text

Parameters:

  • text (String)
  • options (Hash) (defaults to: {})

    options to recognize regex patterns with

Options Hash (options):

  • :self_recognition (Array)

    to recognize chars as itself

Returns:

  • (Array)


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/regex_generator/characters_recognizer.rb', line 11

def self.recognize(text, options = {})
  return [] unless text

  result = []
  text.chars.each do |char|
    PATTERNS.each do |pattern|
      next unless char[pattern]

      escaped_char = Regexp.escape(char)
      res_pattern = escaped_char
      res_pattern = pattern.source if (char.eql?(escaped_char) &&
        !options[:self_recognition]&.include?(escaped_char)) || char[/\s/]

      break result << res_pattern
    end
  end

  result
end