diff options
-rw-r--r-- | src/nre.nim | 4 | ||||
-rw-r--r-- | test/replace.nim | 5 |
2 files changed, 9 insertions, 0 deletions
diff --git a/src/nre.nim b/src/nre.nim index 89680ea5d..b66a1f6da 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 df7227f0b..ff2c4a2b5 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") |