1

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.."

2 Answers 2

4

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))
Sign up to request clarification or add additional context in comments.

2 Comments

Matt Ball - Actually, it only results in a single backslash—but I can see why you'd get confused. When you run the command in the REPL it prints the result as a string literal, in which case it has to show the single backslash as escaped since it's inside the string literal. Try wrapping the whole thing in a println call and you'll see that the result really one has one backslash.
Matt Ball - Ah, sorry, I didn't actually look at the code you posted. The same principle applies though. The pr function prints data in a way that the reader can parse, whereas print outputs data in a human-readable format. Since the data is a string in this case, pr prints a string literal (notice the surrounding quotes), whereas print just outputs the raw string of characters to the console. Change your pr to a print and you'll get the expected output.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.