On Tuesday, August 5, 2014 7:49:21 AM UTC+2, larry google groups wrote: > > I'm working on a website with a frontender who asked to be able to save > JSON maps that contain field names such as: > > "$$hashKey" : "00C" > > The dollar signs are a violation of MongoDB limits on field names, so i > need to convert to something else and then convert back. So I thought I > would convert to * or !. Converting is no problem, but converting back is > not working. I walk the deeply nested JSON objects with: > > (defn walk-deep-structure [next-item function-to-transform-values] > (walk/postwalk > (fn [%] > (if (and (vector? %) (= (count %) 2) (keyword? (first %))) > [(function-to-transform-values %) (second %)] > %)) > next-item)) > > which I call like: > > results (walk-deep-structure @future-data-return (fn [%] > (st/replace (name (first %)) #"\*" "$")))] > > which doesn't work. > > I switch to the repl to test this: > > => (def f (fn [%] (st/replace (name (first %)) #"!" "$"))) > > => (f [:!!username "michael"]) > > StringIndexOutOfBoundsException String index out of range: 1 > java.lang.String.charAt (String.java:695) > > or: > > => (def f (fn [%] (st/replace (name (first %)) #"\*" "$"))) > > => (f [:**username "michael"]) > > StringIndexOutOfBoundsException String index out of range: 1 > java.lang.String.charAt (String.java:695) > > What am I doing wrong? >
If you use a regex as the second parameter of clojure.string/replace, then a $ character followed by a number in the third argument is interpreted as a reference to a captured sub-sequence in the regex ($0, $1, etc.). In your case the $ is not followed by a number as expected, which leads to the exception. To use a literal $ you have to escape it by preceding with a \ (which has to be escaped itself!), or by using re-quote-replacement: user=> (clojure.string/replace "**username" #"\*" "\\$") "$$username" user=> (clojure.string/replace "**username" #"\*" (clojure.string/re-quote-replacement "$")) "$$username" -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups "Clojure" group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.