diff options
-rw-r--r-- | README.asciidoc | 6 | ||||
-rw-r--r-- | src/nre.nim | 7 | ||||
-rw-r--r-- | test/escape.nim | 7 | ||||
-rw-r--r-- | test/testall.nim | 1 |
4 files changed, 21 insertions, 0 deletions
diff --git a/README.asciidoc b/README.asciidoc index 87903b497..dd7b78dc7 100644 --- a/README.asciidoc +++ b/README.asciidoc @@ -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 diff --git a/src/nre.nim b/src/nre.nim index b4ce99c65..d907cae62 100644 --- a/src/nre.nim +++ b/src/nre.nim @@ -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") diff --git a/test/escape.nim b/test/escape.nim new file mode 100644 index 000000000..db5e8a001 --- /dev/null +++ b/test/escape.nim @@ -0,0 +1,7 @@ +import nre, unittest + +suite "escape strings": + test "escape strings": + check("123".escapeRe() == "123") + check("[]".escapeRe() == r"\[\]") + check("()".escapeRe() == r"\(\)") diff --git a/test/testall.nim b/test/testall.nim index 89b661a2a..7b11fbb91 100644 --- a/test/testall.nim +++ b/test/testall.nim @@ -5,3 +5,4 @@ import find import split import match import replace +import escape |