philipbohun.com

Glojure by Example: Regular Expressions

#"..." is a regular expression literal. re-find returns the first match. re-seq returns every match. re-matches succeeds only when the whole string matches.

(println (re-find #"\d+" "id 42"))
(println (re-seq #"\d+" "a 1 b 22"))
(println (re-matches #"\d+" "42"))
(println (re-matches #"\d+" "42a"))

The Go regexp package is also exported. Compile returns the pattern and an error. Methods on the pattern find and replace matches. The capture group is the second element of the submatch.

(let [[pattern err] (regexp.Compile "p([a-z]+)ch")]
  (println (nil? err))
  (println (.FindString pattern "peach punch"))
  (println (vec (.FindStringSubmatch pattern "peach")))
  (println (.ReplaceAllString pattern "a peach" "<fruit>")))

re-matches returns nil when the pattern does not cover the whole string.

$ glj regular-expressions.glj
42
(1 22)
42
nil
true
peach
[peach ea]
a <fruit>

Next example: EDN.