From 447d0e0e8b7f3126ddbf21b44a3d182978805dfe Mon Sep 17 00:00:00 2001 From: Flaviu Tamas Date: Sat, 17 Jan 2015 22:45:23 -0500 Subject: [PATCH] Add more typical string replace --- src/nre.nim | 4 ++++ test/replace.nim | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/src/nre.nim b/src/nre.nim index 89680ea5d2..b66a1f6daa 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -431,3 +431,7 @@ proc replace*(str: string, pattern: Regex, lastIdx = bounds.b result.add(str.substr(lastIdx, str.len - 1)) + +proc replace*(str: string, pattern: Regex, sub: string): string = + return str.replace(pattern, proc (match: RegexMatch): string = + sub % match.captures.toSeq ) diff --git a/test/replace.nim b/test/replace.nim index df7227f0b5..ff2c4a2b57 100644 --- a/test/replace.nim +++ b/test/replace.nim @@ -6,3 +6,8 @@ suite "replace": check("".replace(re"1", proc (v: RegexMatch): string = "1") == "") check(" ".replace(re"", proc (v: RegexMatch): string = "1") == "1 ") check("".replace(re"", proc (v: RegexMatch): string = "1") == "1") + + test "regular replace": + check("123".replace(re"\d", "foo") == "foofoofoo") + check("123".replace(re"(\d)", "$1$1") == "112233") + check("123".replace(re"(\d)(\d)", "$1$2") == "123")