From 00b047a6600b53a6439e9bf78d05894c5dd10297 Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 10 Jan 2015 11:27:46 -0500 Subject: [PATCH] Implement foundation for named captures --- src/nre.nim | 33 ++++++++++++++++++++++++++++++++- test/captures.nim | 7 +++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 test/captures.nim diff --git a/src/nre.nim b/src/nre.nim index feae0c2281..3f06d33bbf 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -2,7 +2,7 @@ import private.pcre as pcre import private.util import tables import unsigned -from strutils import toLower +from strutils import toLower, `%` # PCRE Options {{{ @@ -100,3 +100,34 @@ proc initRegex*(pattern: string, options = "Sx"): Regex = result.pcreExtra = pcre.study(result.pcreObj, 0x0, addr errorMsg) if result.pcreExtra == nil: raise StudyError(msg: $errorMsg) + +proc getinfo[T](self: Regex, opt: cint): T = + let retcode = pcre.fullinfo(self.pcreObj, self.pcreExtra, opt, addr result) + + if retcode < 0: + raise newException(FieldError, "Invalid getinfo for $1, errno $2" % [$opt, $retcode]) + +proc getCaptureCount(self: Regex): int = + # get the maximum number of captures + return getinfo[int](self, pcre.INFO_CAPTURECOUNT) + +type UncheckedArray {.unchecked.}[T] = array[0 .. 0, T] +proc getNameToNumberTable(self: Regex): Table[string, int] = + let entryCount = getinfo[cint](self, pcre.INFO_NAMECOUNT) + let entrySize = getinfo[cint](self, pcre.INFO_NAMEENTRYSIZE) + let table = cast[ptr UncheckedArray[uint8]]( + getinfo[int](self, pcre.INFO_NAMETABLE)) + + result = initTable[string, int]() + + for i in 0 .. 1(?2(?3))(?'v4'4))()")) == + { "v1" : 1, "v2" : 2, "v3" : 3, "v4" : 4 }.toTable())