从不带破折号的字符串创建UUID [英] Creating a UUID from a string with no dashes
问题描述
如何从不带破折号的字符串创建java.util.UUID?
How would I create a java.util.UUID from a string with no dashes?
"5231b533ba17478798a3f2df37de2aD7" => #uuid "5231b533-ba17-4787-98a3-f2df37de2aD7"
推荐答案
p> Clojure的 #uuid
标记的文字是传递到 java.util.UUID / fromString
。并且, fromString
将它分割为 - ,并将其转换为两个 Long
值。 ( UUID 的格式标准化为8-4-4-4-12十六进制数字,但 - 为)
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.)
直接的解决方案是重新插入 - 并使用 java.util.UUID / fromString
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")))
b $ b
如果您想要没有正则表达式的内容,可以使用 ByteBuffer
和 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))))
这篇关于从不带破折号的字符串创建UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!