Replacing * with \* in Clojure
clojure, replace, string
Solution
You have to use 4 backslashes:
> (println (clojure.string/replace "A*B" #"\*" "\\\\*"))
A\*B
nil
>
or, without a regex, it's simply:
> (println (clojure.string/replace "A*B" "*" "\\*"))
A\*B
nil
>
To use this as a regex pattern, use the `re-pattern` function:
> (def p (clojure.string/replace "A*B" #"\*" "\\\\*"))
#'sandbox17459/p
> (println p)
A\*B
nil
> (clojure.string/replace "BLA*BLA" (re-pattern p) "UH")
"BLUHLA"
>
Problem
How do I escape `"*"` to `"\*"` in clojure? Can't seem to get it to work: `(s/replace "A*B" #"*" "*")` produces `"A*B"` (of course) `(s/replace "A*B" #"*" "\*")` fails: `Unsupported escape character: *` `(s/replace "A*B" #"*" "\\*")` produces `"A*B"` again! `(s/replace "A*B" #"*" "\\\*")` fails: `Unsupported escape character: *` again! `(s/replace "A*B" #"\\\\*" "*")` produces `"A\\*B"` I can't get it to produce `A\*B` Any ideas? Thanks