Add escapeRe

This commit is contained in:
Flaviu Tamas
2015-01-18 13:45:56 -05:00
parent 0b24ba0d26
commit 7bce00b4cd
4 changed files with 21 additions and 0 deletions

View File

@@ -78,6 +78,12 @@ If `sub` is a string, then each match is replaced with that string, where the
captures are accessable as `$1`, `$2`, and so on. A literal `$` can be added by
doubling up like so: `$$`.
[[proc-escapere]]
==== escapeRe(string): string
Escapes the string so it doesn't match any special characters. Incompatible
with the Extra flag (`X`).
=== RegexMatch
Represents the result of an execution. On failure, it is `nil`. The available

View File

@@ -291,6 +291,7 @@ proc initRegex(pattern: string, options: string): Regex =
proc re*(pattern: string, options = ""): Regex = initRegex(pattern, options)
# }}}
# Operations {{{
proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): RegexMatch =
new(result)
result.pattern = pattern
@@ -442,3 +443,9 @@ proc replace*(str: string, pattern: Regex,
proc replace*(str: string, pattern: Regex, sub: string): string =
return str.replace(pattern, proc (match: RegexMatch): string =
sub % match.captures.toSeq )
# }}}
let SpecialCharMatcher = re"([\\+*?[^\]$(){}=!<>|:-])"
proc escapeRe*(str: string): string =
str.replace(SpecialCharMatcher, "\\$1")

7
test/escape.nim Normal file
View File

@@ -0,0 +1,7 @@
import nre, unittest
suite "escape strings":
test "escape strings":
check("123".escapeRe() == "123")
check("[]".escapeRe() == r"\[\]")
check("()".escapeRe() == r"\(\)")

View File

@@ -5,3 +5,4 @@ import find
import split
import match
import replace
import escape