summary refs log tree commit diff stats
path: root/src/nre.nim
diff options
context:
space:
mode:
authorOleh Prypin <blaxpirit@gmail.com>2015-01-19 14:33:05 +0200
committerOleh Prypin <blaxpirit@gmail.com>2015-01-19 14:33:05 +0200
commit41c0060e6ddc9b413041a8118e48415783253c40 (patch)
treed9b366e83d65f68aa360d65cdb3ebe972d62af7b /src/nre.nim
parent260ab8b01bb4daa0488232cada81d3a5befa8e91 (diff)
downloadNim-41c0060e6ddc9b413041a8118e48415783253c40.tar.gz
Fix last element when splitting with 0-length match
Diffstat (limited to 'src/nre.nim')
-rw-r--r--src/nre.nim29
1 files changed, 15 insertions, 14 deletions
diff --git a/src/nre.nim b/src/nre.nim
index d907cae62..d98f55889 100644
--- a/src/nre.nim
+++ b/src/nre.nim
@@ -391,6 +391,7 @@ proc split*(str: string, pattern: Regex, maxSplit = -1): seq[string] =
   result = @[]
   var lastIdx = 0
   var splits = 0
+  var bounds: Slice[int]
 
   for match in str.findIter(pattern):
     # upper bound is exclusive, lower is inclusive:
@@ -398,16 +399,12 @@ proc split*(str: string, pattern: Regex, maxSplit = -1): seq[string] =
     # 0123456
     #  ^^^
     # (1, 4)
-    var bounds = match.matchBounds
-
-    if lastIdx == 0 and
-       lastIdx == bounds.a and
-       bounds.a == bounds.b:
-      # "12".split("") would be @["", "1", "2"], but
-      # if we skip an empty first match, it's the correct
-      # @["1", "2"]
-      discard
-    else:
+    bounds = match.matchBounds
+
+    # "12".split("") would be @["", "1", "2"], but
+    # if we skip an empty first match, it's the correct
+    # @["1", "2"]
+    if bounds.a < bounds.b or bounds.a > 0:
       result.add(str.substr(lastIdx, bounds.a - 1))
       splits += 1
 
@@ -420,10 +417,14 @@ proc split*(str: string, pattern: Regex, maxSplit = -1): seq[string] =
     if splits == maxSplit:
       break
 
-  # last match: Each match takes the previous substring,
-  # but "1 2".split(/ /) needs to return @["1", "2"].
-  # This handles "2"
-  result.add(str.substr(lastIdx, str.len - 1))
+  # "12".split("\b") would be @["1", "2", ""], but
+  # if we skip an empty last match, it's the correct
+  # @["1", "2"]
+  if bounds.a < bounds.b or bounds.b < str.len:
+    # last match: Each match takes the previous substring,
+    # but "1 2".split(/ /) needs to return @["1", "2"].
+    # This handles "2"
+    result.add(str.substr(bounds.b, str.len - 1))
 
 proc replace*(str: string, pattern: Regex,
               subproc: proc (match: RegexMatch): string): string =