Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
clojure detect and linkify URLs
; From John Gruber's
; Added a capture group around the protocol so we can distinguish matches that contained it.
(def url-regex #"(?i)\b((?:([a-z][\w-]+:(?:/{1,3}|[a-z0-9%]))|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))")
(defn linkify-urls
"Add A tags around parts of the string that look likely to be URLs."
(let [matcher (re-matcher url-regex text)]
(if-not (.find matcher)
text ; avoid building a StringBuffer (and presumably copying the string) if there were no matches
(let [result (StringBuffer.)]
(loop []
(if (.group matcher 2)
(.appendReplacement matcher result "<a class=\"detected-link\" href=\"$1\">$1</a>")
; If there was no protocol, we need to add one so the browser won't treat this as a relative link.
(.appendReplacement matcher result "<a class=\"detected-link\" href=\"http://$1\">$1</a>"))
(if (.find matcher)
(.toString (.appendTail matcher result))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.