From c67bfcb85cadc1b5b4dfdc036afb6faad4d644cd Mon Sep 17 00:00:00 2001 From: Gears JS Date: Wed, 15 Feb 2023 10:14:09 +0000 Subject: [PATCH] feat: Add regex parser --- lib/parsby/combinators.rb | 17 +++++++++++++++++ spec/parsby/combinators_spec.rb | 8 ++++++++ 2 files changed, 25 insertions(+) diff --git a/lib/parsby/combinators.rb b/lib/parsby/combinators.rb index d1bbc0e..3e94e24 100644 --- a/lib/parsby/combinators.rb +++ b/lib/parsby/combinators.rb @@ -408,5 +408,22 @@ def splicer block.call(parse) end end + + # Matches a regular expression + define_combinator :regex do |regex| + Parsby.new :regex do |target| + position = target.bio.pos + target_string = target.bio.read + + unless target_string.match?(regex) + raise ExpectationFailed.new target + end + + match = target_string.match(regex).to_s + target.bio.restore_to(position + match.length) + + match + end + end end end diff --git a/spec/parsby/combinators_spec.rb b/spec/parsby/combinators_spec.rb index a751d87..c66e7a6 100644 --- a/spec/parsby/combinators_spec.rb +++ b/spec/parsby/combinators_spec.rb @@ -505,4 +505,12 @@ def self.parenthesis expect { test_parser.parse("ad") }.to raise_error Parsby::ExpectationFailed end end + + describe "#regex" do + it "matches a regex to a string" do + expect(regex(/[A-Z][a-z] ./).parse("Hi !")).to eq "Hi !" + expect(regex(/\w+@\w+\.\w+/).parse("user@gmail.com extra")).to eq "user@gmail.com" + expect {regex(/\w+@\w+\.\w+/).parse("user@gmail")}.to raise_error Parsby::ExpectationFailed + end + end end