From 0f4b142c757f7d46071d0cbff959d5c1002d0c05 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 19:10:43 -0500 Subject: [PATCH] Implement toTable(Captures), toSeq(Captures) --- src/nre.nim | 35 +++++++++++++++++++++++++++++++++++ test/captures.nim | 19 +++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/src/nre.nim b/src/nre.nim index 5a5cbaa45d..64ed8c75d8 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -2,6 +2,7 @@ import private.pcre as pcre import private.util import tables import unsigned +from future import lc, `[]` from strutils import toLower, `%` from math import ceil import optional_t @@ -102,6 +103,40 @@ proc `[]`*(self: Captures, name: string): string = ## Will fail with KeyError if `name` is not a real named capture let self = RegexMatch(self) return self.captures[self.pattern.captureNameToId.fget(name)] + +template asTableImpl(cond: bool): stmt {.immediate, dirty.} = + for key in RegexMatch(self).pattern.captureNames: + let nextVal = self[key] + if cond: + result[key] = default + else: + result[key] = nextVal + +proc asTable*(self: Captures, default: string = nil): Table[string, string] = + ## Gets all the named captures and returns them + result = initTable[string, string]() + asTableImpl(nextVal == nil) + +proc asTable*(self: CaptureBounds, default = None[Slice[int]]()): + Table[string, Option[Slice[int]]] = + ## Gets all the named captures and returns them + result = initTable[string, Option[Slice[int]]]() + asTableImpl(nextVal.isNone) + +template asSeqImpl(cond: bool): stmt {.immediate, dirty.} = + result = @[] + for i in 0 .. foo)(?bar)?").exec("foo").get + check(ex1.captures.asTable == {"foo" : "foo", "bar" : nil}.toTable()) + check(ex1.captureBounds.asTable == {"foo" : Some(0..3), "bar" : None[Slice[int]]()}.toTable()) + check(ex1.captures.asTable("") == {"foo" : "foo", "bar" : ""}.toTable()) + + let ex2 = initRegex("(?foo)(?bar)?").exec("foobar").get + check(ex2.captures.asTable == {"foo" : "foo", "bar" : "bar"}.toTable()) + + test "capture sequence": + let ex1 = initRegex("(?foo)(?bar)?").exec("foo").get + check(ex1.captures.asSeq == @["foo", nil]) + check(ex1.captureBounds.asSeq == @[Some(0..3), None[Slice[int]]()]) + check(ex1.captures.asSeq("") == @["foo", ""]) + + let ex2 = initRegex("(?foo)(?bar)?").exec("foobar").get + check(ex2.captures.asSeq == @["foo", "bar"]) +