7

我如何逃到"*"clojure "\*"?似乎无法让它工作:

(s/replace "A*B" #"*" "*")产生 "A*B"(当然)

(s/replace "A*B" #"*" "\*")失败:Unsupported escape character: *

(s/replace "A*B" #"*" "\\*")再次生产 "A*B"

(s/replace "A*B" #"*" "\\\*")失败:Unsupported escape character: *再次!

(s/replace "A*B" #"\\\\*" "*")生产 "A\\*B"

我无法让它产生A\*B 任何想法?谢谢

4

1 回答 1

8

您必须使用 4 个反斜杠:

> (println (clojure.string/replace "A*B" #"\*" "\\\\*"))
A\*B
nil
>  

或者,没有正则表达式,它只是:

> (println (clojure.string/replace "A*B" "*" "\\*"))
A\*B
nil
>  

要将其用作正则表达式模式,请使用以下re-pattern函数:

> (def p (clojure.string/replace "A*B" #"\*" "\\\\*"))
#'sandbox17459/p
> (println p)
A\*B
nil
> (clojure.string/replace "BLA*BLA" (re-pattern p) "UH")
"BLUHLA"
>  
于 2013-07-24T12:37:28.043 回答