user1442023
user1442023

Reputation: 73

Clojure string replace strange behaviour

i think I found a bug in clojure, can anyone explain why the backslash is missing from the output?

(clojure.string/replace "The color? is red." #"[?.]"  #(str "zzz\\j" %1 %1))

=> "The colorzzzj?? is redzzzj.."

Upvotes: 1

Views: 1045

Answers (2)

DaoWen
DaoWen

Reputation: 33019

This isn't a bug. The string returned by the function in the 3rd parameter is parsed for escape sequences so that you can do things like this:

(clojure.string/replace "The color? is red." #"([?.])" "\\$1$1")
; => "The color$1? is red$1."

Notice how the first $ is escaped by the backslash, whereas the second serves as the identifier for a capture group. Change your code to use four backslashes and it works:

(clojure.string/replace "The color? is red." #"[?.]"  #(str "zzz\\\\j" %1 %1))

Upvotes: 4

Ankur
Ankur

Reputation: 33637

Please check the function documentation at: http://clojuredocs.org/clojure_core/clojure.string/replace

Specifically:

Note: When replace-first or replace have a regex pattern as their match argument, dollar sign ($) and backslash (\) characters in the replacement string are treated specially.

Upvotes: 4

Related Questions