How would I create a java.util.UUID from a string with no dashes?
"5231b533ba17478798a3f2df37de2aD7" => #uuid "5231b533-ba17-4787-98a3-f2df37de2aD7"
Clojure's #uuid
tagged literal is a pass-through to java.util.UUID/fromString
. And, fromString
splits it by the "-" and converts it into two Long
values. (The format for UUID is standardized to 8-4-4-4-12 hex digits, but the "-" are really only there for validation and visual identification.)
The straight forward solution is to reinsert the "-" and use java.util.UUID/fromString
.
(defn uuid-from-string [data]
(java.util.UUID/fromString
(clojure.string/replace data
#"(\w{8})(\w{4})(\w{4})(\w{4})(\w{12})"
"$1-$2-$3-$4-$5")))
If you want something without regular expressions, you can use a ByteBuffer
and DatatypeConverter
.
(defn uuid-from-string [data]
(let [buffer (java.nio.ByteBuffer/wrap
(javax.xml.bind.DatatypeConverter/parseHexBinary data))]
(java.util.UUID. (.getLong buffer) (.getLong buffer))))