On Mon, Mar 14, 2011 at 2:17 PM, Daniel Solano Gomez
<cloj...@sattvik.com> wrote:
> On Mon Mar 14 13:02 2011, shuaybi2 shuaybi2 wrote:
>> I have a string such as:
>>
>> "select * from account where acctId = _ACCT-ID_ and acctTyp = _ACCT-TYP_"

There are several clojure libraries that exist to improve the ease and
safety of doing something like this. Amongst them are
clojure.contrib.sql and ClojureQL, which take different approaches.
They all should be sufficient to guard against SQL injection and
should probably be the first place you look.

For the more general question you were asking about how to generically
replace a map of matches-to-replacements though, Daniel did a good job
showing how to use a reduce over the map. That method will call
"replaceAll" once per entry in the map, which is probably fine if you
don't have many substitutions.

Another way to do it is using clojure.string.replace, which has an
often-overlooked third overload which matches with a regex and
replaces with a "mapping function."

Starting with a simple example:
user=>(require '[clojure.string :as s])
nil
user=>(s/replace "a b a" #"a|b" {"a" "1" "b" "2"})
"1 2 1"

In the example, the map was being used as a "replacement function".

---
If you're willing to change your map to use strings as keys and
values, then the previous example is good enough.

Otherwise, because you're wanting to use keywords as your keys, and
arbitratry values for your values, we'll need to use a slightly more
sophisticated replacement function.

(defn key-pattern
    "Create a regex Pattern of the form '<key1>|<key2>', the key names
will be quoted in case they contain special regex characters"
    [m]
    (->> (keys m)
        (map #(java.util.regex.Pattern/quote (name %)))
        (s/join "|")
        java.util.regex.Pattern/compile))

(defn replace-map [text m]
    (s/replace text
       (key-pattern m)
       (fn [field-name]
          (java.util.regex.Matcher/quoteReplacement (str (get m
(keyword field-name)))))))

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

Reply via email to