Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing * with \* in Clojure

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

like image 858
sebi Avatar asked Jul 24 '13 12:07

sebi


1 Answers

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"
>  
like image 186
sloth Avatar answered Oct 12 '22 22:10

sloth