Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clojure equivalent for ruby's gsub

Tags:

regex

clojure

How do i do this in clojure

"text".gsub(/(\d)([ap]m|oclock)\b/, '\1 \2')
like image 426
Surya Avatar asked Sep 16 '10 17:09

Surya


1 Answers

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 regex literal
                   "$1 $2")
"9 oclock"
like image 67
Michał Marczyk Avatar answered Oct 09 '22 20:10

Michał Marczyk