class Regex::Multiplicity

The multiplicity specifies by how much a given expression can be repeated.

Attributes

lower_bound[R]

@return [Integer] The lowest acceptable repetition count

policy[RW]

@return [Symbol] An indicator that specifies how to repeat @see initialize

upper_bound[R]

@return [Integer, Symbol] The highest possible repetition count

Public Class Methods

new(aLowerBound, anUpperBound, aPolicy) click to toggle source

@param aLowerBound [Integer] @param anUpperBound [Integer, Symbol] integer or :more symbol @param aPolicy [Symbol] One of: (:greedy, :lazy, :possessive) @option aPolicy [Symbol] :greedy @option aPolicy [Symbol] :lazy @option aPolicy [Symbol] :possessive

# File lib/regex/multiplicity.rb, line 24
def initialize(aLowerBound, anUpperBound, aPolicy)
  @lower_bound = valid_lower_bound(aLowerBound)
  @upper_bound = valid_upper_bound(anUpperBound)
  @policy = valid_policy(aPolicy)
end

Public Instance Methods

to_str() click to toggle source

@return [String] String representation of the multiplicity.

# File lib/regex/multiplicity.rb, line 31
def to_str
  case upper_bound
    when :more
      case lower_bound
        when 0
          subresult = '*'
        when 1
          subresult = '+'
        else
          subresult = "{#{lower_bound},}"
      end

    when lower_bound
      subresult = "{#{lower_bound}}"
    else
      if [lower_bound, upper_bound] == [0, 1]
        subresult = '?'
      else
        subresult = "{#{lower_bound},#{upper_bound}}"
      end
  end

  policy2suffix = {
    greedy: '',
    lazy: '?',
    possessive: '+'
  }

  return subresult + policy2suffix[policy]
end

Private Instance Methods

valid_lower_bound(aLowerBound) click to toggle source

Validation method. Return the validated lower bound value

# File lib/regex/multiplicity.rb, line 65
def valid_lower_bound(aLowerBound)
  err_msg = "Invalid lower bound of repetition count #{aLowerBound}"
  raise StandardError, err_msg unless aLowerBound.kind_of?(Integer)

  return aLowerBound
end
valid_policy(aPolicy) click to toggle source

Validation method. Return the validated policy value.

# File lib/regex/multiplicity.rb, line 83
def valid_policy(aPolicy)
  err_msg = "Invalid repetition policy '#{aPolicy}'."
  valid_policies = %i[greedy lazy possessive]
  raise StandardError, err_msg unless valid_policies.include? aPolicy

  return aPolicy
end
valid_upper_bound(anUpperBound) click to toggle source

Validation method. Return the validated lower bound value

# File lib/regex/multiplicity.rb, line 73
def valid_upper_bound(anUpperBound)
  err_msg = "Invalid upper bound of repetition count #{anUpperBound}"
  unless anUpperBound.kind_of?(Integer) || (anUpperBound == :more)
    raise StandardError, err_msg
  end

  return anUpperBound
end