tags:

views:

157

answers:

3

How do i do this in clojure

"text".gsub(/(\d)([ap]m|oclock)\b/, '\1 \2')
+3  A: 

That would be replace in the clojure.string namespace. You can find it here.

Use it like so:

(ns rep
  (:use [clojure.string :only (replace)]))
(replace "this is a testing string testing testing one two three" ;; string
         "testing" ;; match
         "Mort") ;; replacement

replace is awesome because the match and replacement can also be string/string or char/char, or you could even do regex pattern/function of the match or string.

Isaac Hodes
Second argument cannot be a '\1 \2' ( which is one match substring 1and match substring 2 ). That is what i am looking for.
Surya
Though `.replaceAll` may be more isomorphic to `gsub`, `replace` can do what you want: if you use a pattern (like in your example) you could use a function to process the result of the regex pattern, and do whatever you wanted. It's actually quite a bit more powerful than `replaceAll`.
Isaac Hodes
+3  A: 

You can use Java's replaceAll method. The call would look like:

(.replaceAll "text" "(\\d)([ap]m|oclock)\\b" "$1 $2")

Note that this will return a new string (like gsub (without the bang) would in ruby). There is no equivalent for gsub! in clojure as java/clojure string are immutable.

sepp2k
yea sorry i meant gsub. Thanks this makes sense.
Surya
+6  A: 

To add to Isaac's answer, this is how you would use clojure.string/replace in this particular occasion:

user> (str/replace "9oclock"
                   #"(\d)([ap]m|oclock)\b"
                   (fn [[_ a b]] (str a " " b)))
                      ; ^- note the destructuring of the match result
                  ; ^- using an fn to produce the replacement 
"9 oclock"

To add to sepp2k's answer, this is how you can take advantage of Clojure's regex literals while using the "$1 $2"gimmick (arguably simpler than a separatefn` in this case):

user> (.replaceAll (re-matcher #"(\d)([ap]m|oclock)\b" "9oclock")
                             ; ^- note the prettier regex
                   "$1 $2")
"9 oclock"
Michał Marczyk
Nice use of destructing hadnt thought of that. But i need a more generic solution so i am going with the second option.
Surya
Michał Marczyk
Thanks for providing an example! I was short on time, but probably should've made my answer clearer. I, too, like the generality and power of the `replace` function, though can see the appeal of the `.replaceAll` method's simplicity.
Isaac Hodes