summary refs log tree commit diff stats
path: root/src/nre.nim
diff options
context:
space:
mode:
authorFlaviu Tamas <tamasflaviu@gmail.com>2015-01-19 15:59:45 -0500
committerFlaviu Tamas <tamasflaviu@gmail.com>2015-01-19 16:04:21 -0500
commitf34a7dc1f5829713b0d076f5d182df6f4beb1761 (patch)
treec306afe24263aa0ab6c6cc77a05a98207818f634 /src/nre.nim
parenta5693675fb36588b12033d3768d41b4c63d31c4b (diff)
downloadNim-f34a7dc1f5829713b0d076f5d182df6f4beb1761.tar.gz
Make replace a template
Also required me to fix a name conflict with the format template
Diffstat (limited to 'src/nre.nim')
-rw-r--r--src/nre.nim21
1 files changed, 14 insertions, 7 deletions
diff --git a/src/nre.nim b/src/nre.nim
index 6c5a1ab35..e56194fd6 100644
--- a/src/nre.nim
+++ b/src/nre.nim
@@ -423,25 +423,32 @@ proc split*(str: string, pattern: Regex, maxSplit = -1): seq[string] =
     # This handles "2"
     result.add(str.substr(bounds.b, str.len - 1))
 
-proc replace*(str: string, pattern: Regex,
-              subproc: proc (match: RegexMatch): string): string =
+template replaceImpl(str: string, pattern: Regex,
+                     replacement: expr): stmt {.immediate, dirty.} =
   # XXX seems very similar to split, maybe I can reduce code duplication
   # somehow?
   result = ""
   var lastIdx = 0
-  for match in str.findIter(pattern):
+  for match {.inject.} in str.findIter(pattern):
     let bounds = match.matchBounds
     result.add(str.substr(lastIdx, bounds.a - 1))
-    result.add(subproc(match))
+    let nextVal = replacement
+    assert(nextVal != nil)
+    result.add(nextVal)
 
     lastIdx = bounds.b
 
   result.add(str.substr(lastIdx, str.len - 1))
+  return result
+
+proc replace*(str: string, pattern: Regex,
+              subproc: proc (match: RegexMatch): string): string =
+  replaceImpl(str, pattern, subproc(match))
 
 proc replace*(str: string, pattern: Regex, sub: string): string =
-  return str.replace(pattern, proc (match: RegexMatch): string =
-    # - 1 because the string numbers are 0-indexed
-    formatStr(sub, match.captures[name], match.captures[id - 1]) )
+  # - 1 because the string numbers are 0-indexed
+  replaceImpl(str, pattern,
+    formatStr(sub, match.captures[name], match.captures[id - 1]))
 
 # }}}