mirror of
https://github.com/nim-lang/Nim.git
synced 2026-05-23 05:09:54 +00:00
Add escapeRe
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
7
test/escape.nim
Normal file
@@ -0,0 +1,7 @@
|
||||
import nre, unittest
|
||||
|
||||
suite "escape strings":
|
||||
test "escape strings":
|
||||
check("123".escapeRe() == "123")
|
||||
check("[]".escapeRe() == r"\[\]")
|
||||
check("()".escapeRe() == r"\(\)")
|
||||
@@ -5,3 +5,4 @@ import find
|
||||
import split
|
||||
import match
|
||||
import replace
|
||||
import escape
|
||||
|
||||
Reference in New Issue
Block a user