Skip to content

Instantly share code, notes, and snippets.

@cljforge
Created December 22, 2015 10:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cljforge/855b95abbb7a289144d7 to your computer and use it in GitHub Desktop.
Save cljforge/855b95abbb7a289144d7 to your computer and use it in GitHub Desktop.
Clojure code to escape regExp characters from string
(def regex-char-esc-smap
(let [esc-chars "()&^%$#!?*."]
(zipmap esc-chars
(map #(str "\\" %) esc-chars))))
(defn str-to-pattern
[string]
(->> string
(replace regex-char-esc-smap)
(reduce str)
re-pattern))
@bfontaine
Copy link

This doesn’t work if you already have a backslash in your string:

(re-matches (str-to-pattern "\\.") "\\.")
; => "\\."
(re-matches (str-to-pattern "\\.") "\\a")
; => "\\a"

(re-matches #"\\\." "\\.")
; => "\\."
(re-matches #"\\\." "\\a")
; => nil

@timrobinson33
Copy link

@bfontaine simply include a backslash inside the esc-chars string (doubled-up obviously)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment