简体   繁体   中英

How to prepend a backslash using clojure.string/replace

I am trying to use clojure.string/replace to escape certain characters like asterisks and backticks with backslashes (like ex*mple -> ex\\*mple ), but I cannot make sense of the function's own escaping rules:

If I try (cs/replace "ex*mple" #"[\\*`]" "\\\\$0") , it treats the $0 literally and returns ex$0mple .

If I try (cs/replace "ex*mple" #"[\\*`]" "\\\\\\\\$0") it adds two slashes: ex\\\\*mple .

What is the right way to do it?

Your second approach, (cs/replace "ex*mple" #"[\\*`]" "\\\\\\\\$0") , is correct. The reason you see two backslashes in the result is because that's how Clojure shows single backslashes in strings. If you print "ex\\\\*mple" , you'll see ex\\*mple .

Clojure uses backslash as an escape character in strings, so backslashes themselves have to be escaped. ex\\*mple is not a valid string in Clojure because \\* is an unsupported escape character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM