Skip to content

Commit

Permalink
Add Regex extractor to problem parser
Browse files Browse the repository at this point in the history
  • Loading branch information
Tobias Becker committed Jan 28, 2022
1 parent e85251b commit 7ae08b1
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
10 changes: 10 additions & 0 deletions ProblemParser/src/ProblemParser.jl
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export FirstRest
export LineMappings
export Lines
export Map
export Extract
export Mappings
export Noop
export Rectangular
Expand Down Expand Up @@ -59,6 +60,13 @@ struct Map <: GrammarElement
func
end

struct Extract <: GrammarElement
regex::Regex
after::Union{GrammarElement,Nothing}
end
Extract() = Extract(r"\d+", Convert())
Extract(regex::Regex) = Extract(regex, nothing)

struct _Mappings <: GrammarElement
splitter::Union{GrammarElement,Nothing}
first_rest::FirstRest
Expand Down Expand Up @@ -103,6 +111,8 @@ Base.parse(apply::Apply, thing) = apply.func(thing)
Base.parse(map::Map, list::AbstractArray) = Base.map(map.func, list)
Base.parse(map::Map, text::AbstractString) = Base.map(map.func, collect(text))

Base.parse(extract::Extract, text::AbstractString) = parse(extract.after, match(extract.regex, text).match)

function Base.parse(mappings::_Mappings, text::AbstractString)
kv_pairs = parse(mappings.splitter, text)
parse(mappings.first_rest, kv_pairs) |> Dict
Expand Down
16 changes: 16 additions & 0 deletions ProblemParser/test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -198,4 +198,20 @@ end
([8, 10], "k") => "kklxkkkqkkkkk",
([3, 4], "h") => "hrht",
)

not_just_lines = """
--- scanner 0 ---
0,2
4,1
3,3
--- scanner 1 ---
-1,-1
-5,0
-2,1
"""
@test parse(Blocks(FirstRest(Lines(), Extract(), Lines(Split(',', Convert())))), not_just_lines) == [
(0, [[0, 2], [4, 1], [3, 3]]),
(1, [[-1, -1], [-5, 0], [-2, 1]]),
]
end

0 comments on commit 7ae08b1

Please sign in to comment.