Replaces all instances of 'pattern' in 'string' with
'replacement'. Like Ruby's 'String#gsub'.
If (ifn? replacment) is true, the replacement is called with the
match.
user=> (def examplestr (str "jack and jill" \newline "went up the hill")) #'user/examplestr user=> (println examplestr) jack and jill went up the hill nil user=> (println (re-gsub #"\n" " " examplestr)) jack and jill went up the hill nil
(defn re-gsub
"Replaces all instances of 'pattern' in 'string' with
'replacement'. Like Ruby's 'String#gsub'.
If (ifn? replacment) is true, the replacement is called with the
match.
"
[^java.util.regex.Pattern regex replacement ^String string]
(if (ifn? replacement)
(let [parts (vec (re-partition regex string))]
(apply str
(reduce (fn [parts match-idx]
(update-in parts [match-idx] replacement))
parts (range 1 (count parts) 2))))
(.. regex (matcher string) (replaceAll replacement))))
Comments top
No comments for re-gsub. Log in to add a comment.