How do i do this in clojure
"text".gsub(/(\d)([ap]m|oclock)\b/, '\1 \2')
How do i do this in clojure
"text".gsub(/(\d)([ap]m|oclock)\b/, '\1 \2')
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.
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.
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 separate
fn` in this case):
user> (.replaceAll (re-matcher #"(\d)([ap]m|oclock)\b" "9oclock")
; ^- note the prettier regex
"$1 $2")
"9 oclock"