summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorflywind <43030857+xflywind@users.noreply.github.com>2020-11-24 19:37:41 +0800
committerGitHub <noreply@github.com>2020-11-24 12:37:41 +0100
commit823a71380d9c52c224669fe0dfcf5601619978bd (patch)
treec65bdee328bcf5326f30be24e3be4e75049fc40f
parente4d0f9f3de3b62549fd6503e724a047abbadf03f (diff)
downloadNim-823a71380d9c52c224669fe0dfcf5601619978bd.tar.gz
fix #16103 (#16109) [backport:1.0]
* fix #16103

* docs
-rw-r--r--lib/impure/nre.nim26
1 files changed, 21 insertions, 5 deletions
diff --git a/lib/impure/nre.nim b/lib/impure/nre.nim
index 4696f7322..bd17c713e 100644
--- a/lib/impure/nre.nim
+++ b/lib/impure/nre.nim
@@ -68,7 +68,6 @@ from pcre import nil
 import nre/private/util
 import tables
 from strutils import `%`
-from math import ceil
 import options
 from unicode import runeLenAt
 
@@ -742,8 +741,25 @@ proc replace*(str: string, pattern: Regex, sub: string): string =
   replaceImpl(str, pattern,
     formatStr(sub, match.captures[name], match.captures[id - 1]))
 
-let SpecialCharMatcher = re"([\\+*?[^\]$(){}=!<>|:-])"
-proc escapeRe*(str: string): string =
-  ## Escapes the string so it doesn’t match any special characters.
+proc escapeRe*(str: string): string {.gcsafe.} =
+  ## Escapes the string so it doesn't match any special characters.
   ## Incompatible with the Extra flag (``X``).
-  str.replace(SpecialCharMatcher, "\\$1")
+  ##
+  ## Escaped char: `\ + * ? [ ^ ] $ ( ) { } = ! < > | : -`
+  runnableExamples:
+    doAssert escapeRe("fly+wind") == "fly\\+wind"
+    doAssert escapeRe("!") == "\\!"
+    doAssert escapeRe("nim*") == "nim\\*"
+
+  #([\\+*?[^\]$(){}=!<>|:-])
+  const SpecialCharMatcher = {'\\', '+', '*', '?', '[', '^', ']', '$', '(',
+                              ')', '{', '}', '=', '!', '<', '>', '|', ':',
+                              '-'}
+
+  for c in items(str):
+    case c
+    of SpecialCharMatcher:
+      result.add("\\")
+      result.add(c)
+    else:
+      result.add(c)