问题描述
如何从没有破折号的字符串创建 java.util.UUID?
How would I create a java.util.UUID from a string with no dashes?
"5231b533ba17478798a3f2df37de2aD7" => #uuid "5231b533-ba17-4787-98a3-f2df37de2aD7"
推荐答案
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")))
如果你想要没有正则表达式的东西,你可以使用 ByteBuffer
和 DatatypeConverter
.
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))))
这篇关于从没有破折号的字符串创建 UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论