Skip to content

Instantly share code, notes, and snippets.

@alainravet
Created January 15, 2016 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alainravet/a7c2b0ba303e813871b6 to your computer and use it in GitHub Desktop.
Save alainravet/a7c2b0ba303e813871b6 to your computer and use it in GitHub Desktop.
a basic Regexp-based parser
# what: a Regexp-based parser. alainravet - 2016 jan
SYNTAX_RULES = {
/^PRINT\b/ => {
/^PRINT\s*\z/ => :new_line_command,
/^PRINT (.*)/ => :print_command,
},
/HELP/i => :help_command,
}
def command_and_params_for(rules_subtree, text)
captures = nil
_, command_or_rules_subtree = rules_subtree.detect{|pattern, _command_or_rules_subtree|
match = pattern.match(text)
captures = match.captures if match
}
case command_or_rules_subtree
when Symbol
command = command_or_rules_subtree
parameters = captures
[command, parameters]
when Hash
rules_subtree = command_or_rules_subtree
command_and_params_for(rules_subtree, text)
end
end
# -- TEST -- TEST -- TEST -- TEST -- TEST -- TEST -- TEST -- TEST
def assert_equal(expected, actual)
unless expected == actual
raise "\n*** ERROR: \n\texpected: #{expected.inspect}\n\tfound: #{actual.inspect}"
end
end
assert_equal [:help_command, [] ], command_and_params_for(SYNTAX_RULES, 'HELP')
assert_equal [:new_line_command, [] ], command_and_params_for(SYNTAX_RULES, 'PRINT')
assert_equal [:print_command , ["hello world"]], command_and_params_for(SYNTAX_RULES, 'PRINT hello world')
puts "SUCCESS"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment