从没有破折号的字符串创建 UUID

编程入门 行业动态 更新时间:2024-10-23 10:21:13
本文介绍了从没有破折号的字符串创建 UUID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从没有破折号的字符串创建 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")))

如果你想要没有正则表达式的东西,你可以使用 ByteBufferDatatypeConverter.

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:关键词]

本文发布于:2023-03-27 09:05:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/686612.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:破折号   字符串   UUID

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!