Class: TRuby::ParserCombinator::Regex

Inherits:
Parser
  • Object
show all
Defined in:
lib/t_ruby/parser_combinator.rb

Overview

Parse using regex

Instance Method Summary collapse

Methods inherited from Parser

#<<, #>>, #between, #flat_map, #label, #lookahead, #many, #many1, #map, #not_followed_by, #optional, #sep_by, #sep_by1, #|

Constructor Details

#initialize(pattern, description = nil) ⇒ Regex

Returns a new instance of Regex.



163
164
165
166
# File 'lib/t_ruby/parser_combinator.rb', line 163

def initialize(pattern, description = nil)
  @pattern = pattern.is_a?(Regexp) ? pattern : Regexp.new("^#{pattern}")
  @description = description || @pattern.inspect
end

Instance Method Details

#parse(input, position = 0) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
# File 'lib/t_ruby/parser_combinator.rb', line 168

def parse(input, position = 0)
  remaining = input[position..]
  match = @pattern.match(remaining)

  if match&.begin(0)&.zero?
    matched = match[0]
    ParseResult.success(matched, input, position + matched.length)
  else
    ParseResult.failure("Expected #{@description}", input, position)
  end
end