From 7ae08b1a0a7dc1a4ed7e1e9e1f9f6240dab7d9ae Mon Sep 17 00:00:00 2001 From: Tobias Becker Date: Fri, 28 Jan 2022 15:43:48 +0100 Subject: [PATCH] Add Regex extractor to problem parser --- ProblemParser/src/ProblemParser.jl | 10 ++++++++++ ProblemParser/test/runtests.jl | 16 ++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/ProblemParser/src/ProblemParser.jl b/ProblemParser/src/ProblemParser.jl index 7015fc6..ddec494 100644 --- a/ProblemParser/src/ProblemParser.jl +++ b/ProblemParser/src/ProblemParser.jl @@ -7,6 +7,7 @@ export FirstRest export LineMappings export Lines export Map +export Extract export Mappings export Noop export Rectangular @@ -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 @@ -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 diff --git a/ProblemParser/test/runtests.jl b/ProblemParser/test/runtests.jl index 10c8f76..9904655 100644 --- a/ProblemParser/test/runtests.jl +++ b/ProblemParser/test/runtests.jl @@ -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