View Category

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
clojure
(if (re-matches #"[A-Z][a-z]+" "Hello")
(println "ok"))

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
clojure
(if-let [groups (re-matches #"one (.*) three" "one two three")]
(println (second groups)))

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
clojure
(if (re-find #"\d+" "abc 123 @#$")
(println "ok"))

Loop through a string matching a regex and performing an action for each match

Create a list [fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
clojure
(let [matcher (re-matcher #"\((\w+)\):(\d+)" "(fish):1 sausage (cow):3 tree (boat):4")]
(loop [match (re-find matcher)
lst []]
(if match
(recur (re-find matcher) (conj lst (str (second match) (nth match 2))))
lst)))

Replace the first regex match in a string with a static string

Transform "Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
clojure
(.replaceFirst (re-matcher #"e" "Red Green Blue") "*")

Replace all regex matches in a string with a static string

Transform "She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
clojure
(.replaceAll (re-matcher #"se\w+" "She sells sea shells") "X")

Replace all regex matches in a string with a dynamic string

Transform "The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
clojure
(def *string* "The {Quick} Brown {Fox}")
(def *regex* (re-pattern #"\{(\w+)\}"))

(println
(loop [result ""
src *string*
replace-strs (re-seq *regex* *string*)]
(if (empty? src)
result
(let [[match replacement] (first replace-strs)]
(if (= (first src) (first match))
; At the beginning of a sequence that should be replaced.
; Do replacement of a single match
(recur (str result (apply str (reverse replacement)))
(drop (count match) src)
(rest replace-strs))
; else, just copy one char from the source to the result
(recur (str result (first src))
(rest src)
replace-strs))))))
(clojure.string/replace "The {Quick} Brown {Fox}"
#"\{(\w+)\}"
(fn [[_ word]] (apply str (reverse word))))