Class: Regexp::MatchLength

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/regexp_parser/expression/methods/match_length.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(exp, opts = {}) ⇒ MatchLength

Returns a new instance of MatchLength.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/regexp_parser/expression/methods/match_length.rb', line 9

def initialize(exp, opts = {})
  self.exp_class = exp.class
  self.min_rep = exp.repetitions.min
  self.max_rep = exp.repetitions.max
  if (base = opts[:base])
    self.base_min = base
    self.base_max = base
    self.reify = ->{ '.' * base }
  else
    self.base_min = opts.fetch(:base_min)
    self.base_max = opts.fetch(:base_max)
    self.reify = opts.fetch(:reify)
  end
end

Class Method Details

.of(obj) ⇒ Object



4
5
6
7
# File 'lib/regexp_parser/expression/methods/match_length.rb', line 4

def self.of(obj)
  exp = obj.is_a?(Regexp::Expression::Base) ? obj : Regexp::Parser.parse(obj)
  exp.match_length
end

Instance Method Details

#each(opts = {}) ⇒ Object



24
25
26
27
28
29
30
31
32
33
# File 'lib/regexp_parser/expression/methods/match_length.rb', line 24

def each(opts = {})
  return enum_for(__method__, opts) unless block_given?
  limit = opts[:limit] || 1000
  yielded = 0
  (min..max).each do |num|
    next unless include?(num)
    yield(num)
    break if (yielded += 1) >= limit
  end
end

#endless_eachObject



35
36
37
38
# File 'lib/regexp_parser/expression/methods/match_length.rb', line 35

def endless_each
  return enum_for(__method__) unless block_given?
  (min..max).each { |num| yield(num) if include?(num) }
end

#fixed?Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/regexp_parser/expression/methods/match_length.rb', line 44

def fixed?
  min == max
end

#include?(length) ⇒ Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/regexp_parser/expression/methods/match_length.rb', line 40

def include?(length)
  test_regexp.match?('X' * length)
end

#inspectObject



60
61
62
63
# File 'lib/regexp_parser/expression/methods/match_length.rb', line 60

def inspect
  type = exp_class.name.sub('Regexp::Expression::', '')
  "#<#{self.class}<#{type}> min=#{min} max=#{max}>"
end

#maxObject



52
53
54
# File 'lib/regexp_parser/expression/methods/match_length.rb', line 52

def max
  max_rep * base_max
end

#minObject



48
49
50
# File 'lib/regexp_parser/expression/methods/match_length.rb', line 48

def min
  min_rep * base_min
end

#minmaxObject



56
57
58
# File 'lib/regexp_parser/expression/methods/match_length.rb', line 56

def minmax
  [min, max]
end

#to_reObject



65
66
67
# File 'lib/regexp_parser/expression/methods/match_length.rb', line 65

def to_re
  "(?:#{reify.call}){#{min_rep},#{max_rep unless max_rep == Float::INFINITY}}"
end