Skip to content

Instantly share code, notes, and snippets.

View Mikhail-Borisov's full-sized avatar

Mikhail Borisov Mikhail-Borisov

View GitHub Profile
@Mikhail-Borisov
Mikhail-Borisov / named_regex.clj
Last active November 8, 2020 10:51
Clojure macro for regex that returns named capture groups as a map
(defmacro mk-named-regex-fn
"Given an expression that returns a string returns a function
that given a string returns nil if pattern did not match
and a map of named groups if pattern matches.
Usage: ((regex \"(?<name>[a-zA-Z]+)\") \"John\") => {\"name\" \"John\"}"
[regex-string-expression]
(let [regex-string (eval regex-string-expression)
re-group-regex #"(?<!\\)(?:\\\\)*\((?:\?<(\w+)>|[^?])"
pattern (re-pattern regex-string)