Class: Regexp::Template

Inherits:
Object
  • Object
show all
Includes:
TerminalFormattingSupport
Defined in:
lib/core_ext/regexp.rb

Constant Summary collapse

MATCHERS =
{
  any:".",
  alpha:"[a-zA-Z]",
  numeric:"\\d",
  line_end:"$",
  line_start:"^",
  nonnumeric:"\\D",
  whitespace:"\\s",
  alphanumeric:"\\w",
  nonwhitespace:"\\S",
  nonalphanumeric:"\\W"
}
TYPE_MATCHER_DEFAULTS =
{
  string:".*",
  integer:"\\d*",
  decimal:"(\\d*.?\\d*)",
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from TerminalFormattingSupport

included

Constructor Details

#initialize(**args) ⇒ Template

Returns a new instance of Template.



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/core_ext/regexp.rb', line 50

def initialize(**args)
  if(args.keys.length == 0)
    @rx = Regexp.new("")
  elsif(args[:source_rx].is_a?(String))
    @rx = Regexp.new(args[:source_rx])
  elsif(args[:source_rx].is_a?(Regexp))
    @rx = args[:source_rx]
  elsif(!!args[:atoms] && args[:atoms].is_a?(Array))
    @atoms = args[:atoms]
    set_regex_from_atoms
  end
  @type_matchers = {}.merge(Template::TYPE_MATCHER_DEFAULTS)

  if(!@atoms)
    self.analyze
  end
end

Instance Attribute Details

#atomsObject (readonly)

Returns the value of attribute atoms.



45
46
47
# File 'lib/core_ext/regexp.rb', line 45

def atoms
  @atoms
end

#rxObject (readonly)

Returns the value of attribute rx.



45
46
47
# File 'lib/core_ext/regexp.rb', line 45

def rx
  @rx
end

Class Method Details

.capture_group(atoms, **args) ⇒ Object



46
47
48
# File 'lib/core_ext/regexp.rb', line 46

def self.capture_group(atoms,**args)
  return Regexp::Template.new(atoms:[:placeholder_template]).capture_group(atoms,**args)
end

.count(count) ⇒ Object



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/core_ext/regexp.rb', line 299

def self.count(count)
  if(count == :any)
    return "*"
  end
  # if(count.is_a? Symbol)
  if(count.to_s.match(/\>(?<count>\d*)$/))
    count_number = count.to_s.match(/\>(?<count>\d*)/)[:count].to_i
    return "+" if(count_number == 0)
    return "{#{count_number},}"
  elsif(count.to_s.match(/0_or_1/))
    return "?"
  elsif(count.to_s.match(/\>(?<count_min>\d*)_\<(?<count_max>\d*)/)) # Example: count(">3_<5".to_sym) for "greater than 3 less than 5"
    counts = count.match(/\>(?<count_min>\d*)_\<(?<count_max>\d*)/)
    count_min = counts[:count_min].to_i
    count_max = counts[:count_max].to_i
    return "{#{count_min},#{count_max}}"
  elsif(count.to_s.match(/(?<count>\d*)/))
    return"{#{count.to_s.match(/(?<count>\d*)/)[:count].to_i}}"
  end
end

.get_atom(**args) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/core_ext/regexp.rb', line 236

def self.get_atom(**args)     # args[:match] ":any, :numeric, :alphanumeric, etc, also ex: :except_numeric"
                              # args[:count] see self.count
                              # args[:string] for 'literal' text to be matched
  if(!args[:types])
    args[:types] = TYPE_MATCHER_DEFAULTS
  else
    args[:types] = args[:types]
  end

  result = ""
  if(!!args[:match])

    if(args[:match].to_s.include?('except_'))
      args[:match] = args[:match].split("_")[1]
      except = true
    else
      except = false
    end
    if(MATCHERS.keys.include?(args[:match]))
      result = MATCHERS[args[:match].to_sym]
      if(!!args[:count])
        result = "#{result}#{self.count(args[:count])}"
      end
    elsif(args[:types].keys.include?(args[:match]))
      result = "#{args[:types][args[:match].to_sym].to_s}"
    end
  elsif(!!args[:string])
    if(args[:string].length == 2 && args[:string] == Regexp.escape(args[:string][1]))
      result = "literal_#{args[:string][1]}"
    else
      result = args[:string]
    end
  end

  if(!!except)
    result = "[^#{result}]"
  end
  return result.to_sym
end

.group(atoms) ⇒ Object



333
334
335
# File 'lib/core_ext/regexp.rb', line 333

def self.group(atoms)
  return "[#{atoms.join("")}]"
end

Instance Method Details

#<<(o) ⇒ Object



79
80
81
# File 'lib/core_ext/regexp.rb', line 79

def <<(o)
  self.push(o)
end

#add_type(type_name, matcher) ⇒ Object



85
86
87
# File 'lib/core_ext/regexp.rb', line 85

def add_type(type_name, matcher)
  @type_matchers[type_name.to_sym] = matcher
end

#analyzeObject



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/core_ext/regexp.rb', line 208

def analyze
  if(!!@rx && !!@rx.source)
    src = @rx.source
  end

  current_segment = ""
  current_atom = {}
  atom_complete = false
  while(!atom_complete)
    src.split('').each do |char|
      current_segment = "#{current_segment}#{char}"
      if(char == "\\")
        current_atom[:escaped] = true
      end
      if(char == ".")
        current_atom[:match] = :any
      end
      if(char == "*")
        current_atom[:count] = :any
      end
    end
  end
end

#capture_group(atoms, **args) ⇒ Object



319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'lib/core_ext/regexp.rb', line 319

def capture_group(atoms,**args)
  if(!atoms.is_a?(Array))
    atoms = [atoms]
  end
  if(args[:name])
    atoms.unshift("?<#{args[:name]}>".to_sym)
  end
  atoms.unshift(:"(")
  atoms.push(:")")
  def atoms.to_sym
    self.map{|a| render_atom(a) }.join('').to_sym
  end
  return atoms
end

#count(count) ⇒ Object



296
297
298
# File 'lib/core_ext/regexp.rb', line 296

def count(count)
  self.class.count(count)
end

#describe(atom) ⇒ Object



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/core_ext/regexp.rb', line 151

def describe(atom)
  matchers = {}
  match_count = "exactly 1 instance"
  if(atom.to_s[atom.to_s.length-1] == "*")
    match_count = "any number of"
  elsif(atom.to_s[atom.to_s.length-1] == "?")
    match_count = "zero or one"
  elsif(atom.to_s[atom.to_s.length-1] == "+")
    match_count = "1 or more"
  elsif(atom.to_s.match(/\{(?<count>.*)\}\z/))
    match_count_data = atom.to_s.match(/\{(?<count>.*)\}\z/)[:count]
    if(match_count_data.split(',').length == 2)
      match_count = "between #{match_count_data.split(',').first} and #{match_count_data.split(',').last}"
    elsif(match_count_data > 1)
      match_count = "exactly #{match_count_data}"
    end
  end

  if(atom.to_s.include?("literal_"))
    desc = "#{atom.to_s.gsub("_"," ")}"
    color= :yellow
  elsif(atom.to_s[0] == "(" && atom.to_s[atom.length-1] == ")")
    desc = "#{self.preview(atom.to_s[1,atom.length-1],:capture)}"
  elsif(atom.to_s[0] == "\\" && self.class::MATCHERS.keys.include?(atom.to_s[1]))
    desc = "#{self.class::MATCHERS[atom.to_s[1]]} characters"
    color= :yellow
  elsif(@type_matchers.values.include?(atom.to_s))
    matcher_name = (@type_matchers.select{|k| @type_matchers[k] == atom.to_s}.first).first.to_s
    desc  = "#{matcher_name}"
    type_matcher = true
    color = {r:4,b:0,g:4}
  elsif(atom.to_s[0] == "\\" && atom.length <= 3 && !self.class::MATCHERS.keys.include?(atom.to_s[1]))
    desc = "literal #{atom}"
    color= :yellow
  else
    desc = @terminal.rbg(r:0,b:5,g:0, text:"\"#{atom}\"")
  end
  if(!type_matcher)
    desc = "#{match_count} of #{@terminal.add_formatting(desc, color)}"
    return desc.gsub(" of of "," of ")
  else
    desc[0] = desc[0].upcase
    if("aeiou".include?(desc[0,1].downcase))
      article = "an"
    else
      article = "a"
    end
    if(!!color && color.is_a?(Hash))
      color[:text] = desc
      desc = "#{article} #{@terminal.rbg(**color)}"
    elsif(!!color)
      desc = "#{article} #{@terminal.add_formatting(desc, color)}"
    else
      desc = "#{article} #{desc}."
    end
  end
end

#get_atom(**args) ⇒ Object



232
233
234
# File 'lib/core_ext/regexp.rb', line 232

def get_atom(**args)
  self.class.get_atom(**args)
end

#group(atoms) ⇒ Object



336
337
338
# File 'lib/core_ext/regexp.rb', line 336

def group(atoms)
  return "[#{atoms.join("")}]"
end

#line_endObject



293
294
295
# File 'lib/core_ext/regexp.rb', line 293

def line_end
  return "$"
end

#line_startObject



290
291
292
# File 'lib/core_ext/regexp.rb', line 290

def line_start
  return "^"
end

#literal(atom_string) ⇒ Object



287
288
289
# File 'lib/core_ext/regexp.rb', line 287

def literal(atom_string)
  return "#{self.escape(atom_string.to_s)}"
end

#preview(parent_type = nil) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/core_ext/regexp.rb', line 88

def preview(parent_type=nil)
  numbering = @atoms.map.with_index do |a, index|
    atom_text = render_atom(a)
    # source = @rx.source.gsub(atom_text, atom_text+"|")
    # spacer_count = (atom_text+"|").length/2
    spacer_count = (atom_text).length/2
    "#{" "*(spacer_count-1)}##{index}#{" "*(spacer_count)}"
  end
  @terminal = Terminal.new()
  @terminal.clear_terminal
  rx_source = @rx.source
  descriptions = []
  if(!parent_type)
    @atoms.map.with_index do |a,index|
      if(a.is_a?(Array) && a[0] == :"(" && a[a.length-1] == :")")
        stringified = a.map(&:to_s).join('')
        rx_source = rx_source.gsub(stringified,@terminal.rbg(r:0,b:0,g:5, text:stringified))
        subatoms = a[1,a.length-2]
        if(subatoms[0].to_s.start_with?("?<"))
          name = subatoms.shift
          name = name.to_s.match(/\?\<(?<name>.*)\>/)[:name]
          name = "#{name}"
        else
          name = "anonymous_capture_group"
        end
        if(subatoms.length == 1)
          a =  "#{@terminal.rbg(r:0,b:0,g:5, text:"Capture group \"#{name}\"")} captures #{self.describe(subatoms.first)}"
        elsif(subatoms.length == 2)
          a =    "#{@terminal.rbg(r:0,b:0,g:5, text:"Capture group \"#{name}\"")} captures #{self.describe(subatoms[0])} and #{self.describe(subatoms[0])}"
        else
          subatoms = subatoms.map{|s| self.describe(s)}
          last_subatom = subatoms.pop
        a =    "#{@terminal.rbg(r:0,b:0,g:5, text:"Capture group \"#{name}\"")} captures #{subatoms.join(',')} and #{last_subatom}"
        end
      else
        rx_source = rx_source.gsub(a.to_s,@terminal.rbg(r:0,b:5,g:1, text:a.to_s))
        a =  "#{@terminal.rbg(r:0,b:5,g:1, text:"\"#{a}\"")} matches #{self.describe(a)}"
      end
      descriptions << "##{index}. #{a}"
    end
  elsif(parent_type == :capture)
    @atoms.map do |a|
      if(a.to_s.include?("literal_"))
        "#{a.to_s.gsub("_"," ")}"
      elsif(a.to_s[0] == "(" && a.to_s[a.length-1] == ")")
        "#{self.preview(a.to_s[1,a.length-1],:capture)}"
      elsif(a.to_s[0] == "\\" && matchers.keys.include?(a.to_s[1]))
        "#{matchers[a]}"
      elsif(a.to_s[0] == "\\" && a.length <= 3 && !matchers.keys.include?(a.to_s[1]))
        "literal #{a}"
      else
        "#{a}"
      end
    end
  end
  indent = 1
  indent_str = "\t"*indent
  puts "\n"*2
  puts "#{indent_str}#{rx_source}"
  puts "#{indent_str}#{@terminal.add_formatting(numbering.join(''), :yellow)}"
  descriptions.each{|desc| puts "#{indent_str}#{desc}" }
  return
end

#push(o) ⇒ Object



70
71
72
73
74
75
76
77
78
# File 'lib/core_ext/regexp.rb', line 70

def push(o)
  if(o.is_a? Regexp)
    o = o.source
  elsif(o.is_a? Regexp::Template)
    o = o.rx.source
  end
  @atoms << o
  set_regex_from_atoms
end

#render_atom(atom) ⇒ Object



276
277
278
279
280
281
282
283
284
285
286
# File 'lib/core_ext/regexp.rb', line 276

def render_atom(atom)
  if(atom.is_a? Array)
    atom = atom.map(&:to_s).join('')
  end
  atom_str = atom.to_s
  if(atom_str.include?("literal_"))
    return self.escape(atom_str.split("_").last)
  else
    return atom_str
  end
end

#set_regex_from_atomsObject



67
68
69
# File 'lib/core_ext/regexp.rb', line 67

def set_regex_from_atoms
  @rx = Regexp.new(@atoms.map{|a| render_atom(a) }.join(""))
end

#typesObject



82
83
84
# File 'lib/core_ext/regexp.rb', line 82

def types
  return @type_matchers.keys
end