Skip to content

Commit

Permalink
feat: Add regex parser
Browse files Browse the repository at this point in the history
  • Loading branch information
GearsDatapacks committed Feb 15, 2023
1 parent a03563a commit c67bfcb
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/parsby/combinators.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
8 changes: 8 additions & 0 deletions spec/parsby/combinators_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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("[email protected] extra")).to eq "[email protected]"
expect {regex(/\w+@\w+\.\w+/).parse("user@gmail")}.to raise_error Parsby::ExpectationFailed
end
end
end

0 comments on commit c67bfcb

Please sign in to comment.