konr
konr

Reputation: 2565

How can I read strings with backslashes?

Apparently I can't read-string some strings, like

user> (read-string "\" \\ABC \"")
RuntimeException Unsupported escape character: \A  clojure.lang.Util.runtimeException (Util.java:219)
user> 

Is there a way around that?

Thanks!

Upvotes: 3

Views: 1217

Answers (1)

DanLebrero
DanLebrero

Reputation: 8593

I assume that you want to end up with a string that when you print its "\ABC", so:

user=> (println "\\ABC")
\ABC
nil

As you see, the reader needs two "\". As read-string expects the string to be a valid Clojure expression and from your example you are trying to read a string that contains a string, you need to escape both the " (as you are doing) and the two \ :

user=> (def s (read-string "\" \\\\AB\""))
#'user/s
user=> (class s)
java.lang.String
user=> (println s)
 \AB
nil
user=> s
" \\AB"

Upvotes: 1

Related Questions