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

时间:2021-05-26 22:50:54

How would I create a java.util.UUID from a string with no dashes?

如何创建java.util。从一个没有破折号的字符串的UUID ?

"5231b533ba17478798a3f2df37de2aD7" => #uuid "5231b533-ba17-4787-98a3-f2df37de2aD7"

10 个解决方案

#1


14  

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.)

Clojure的#uuid标记文字是对java.util.UUID/fromString的传递。并且,fromString将其拆分为“-”并将其转换为两个长值。(UUID的格式为8-4-4-4-12十六进制数字,但“-”实际上只用于验证和视觉识别。)

The straight forward solution is to reinsert the "-" and use java.util.UUID/fromString.

直接的解决方案是重新插入“-”并使用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.

如果您想要一些没有正则表达式的东西,可以使用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))))

#2


26  

tl;dr

java.util.UUID.fromString(
    "5231b533ba17478798a3f2df37de2aD7"
    .replaceFirst( 
        "(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", "$1-$2-$3-$4-$5" 
    )
).toString()

5231b533-ba17-4787-98a3-f2df37de2ad7

5231年b533 ba17 - 4787 - 98 - a3 - f2df37de2ad7

Bits, Not Text

A UUID is a 128-bit value. A UUID is not actually made up of letters and digits, it is made up of bits. You can think of it as describing a very, very large number.

UUID是128位的值。UUID实际上并不是由字母和数字组成的,而是由位组成的。你可以把它想象成一个非常非常大的数字。

We could display those bits as a one hundred and twenty eight 0 & 1 characters.

我们可以把这些位显示为一百二十八0和1个字符。

0111 0100 1101 0010 0101 0001 0101 0110 0110 0000 1110 0110 0100 0100 0100 1100 1010 0001 0111 0111 1010 1001 0110 1110 0110 0111 1110 1100 1111 1100 0101 1111

011101001101101101101001001001001100110011001100110011001100110011001101101011010110110110110110110110110110110110110110110110011001

Humans do not easily read bits, so for convenience we usually represent the 128-bit value as a hexadecimal string made up of letters and digits.

人类不容易读取比特,因此为了方便起见,我们通常将128位的值表示为由字母和数字组成的十六进制字符串。

74d25156-60e6-444c-a177-a96e67ecfc5f

74 d25156 - 60 - e6 - 444 c - a177 a96e67ecfc5f

Such a hex string is not the UUID itself, only a human-friendly representation. The hyphens are added per the UUID spec as canonical formatting, but are optional.

这样的十六进制字符串不是UUID本身,而是一种对人友好的表示。在UUID规范中添加连字符作为规范格式,但是是可选的。

74d2515660e6444ca177a96e67ecfc5f

74年d2515660e6444ca177a96e67ecfc5f

By the way, the UUID spec clearly states that lowercase letters must be used when generating the hex string while uppercase should be tolerated as input. Unfortunately, many implementations violate that lowercase-generation rule, including those from Apple, Microsoft, and others. See my blog post.

顺便说一下,UUID规范清楚地指出,在生成十六进制字符串时必须使用小写字母,而大写应该作为输入被容忍。不幸的是,许多实现违反了小写生成规则,包括来自苹果、微软和其他的规则。看我的博客。


The following refers to Java, not Clojure.

以下是Java,而不是Clojure。

In Java 7 (and earlier), you may use the java.util.UUID class to instantiate a UUID based on a hex string with hyphens as input. Example:

在Java 7(和更早的版本)中,您可以使用Java .util。UUID类以带有连字符的十六进制字符串为输入实例化UUID。例子:

java.util.UUID uuidFromHyphens = java.util.UUID.fromString("6f34f25e-0b0d-4426-8ece-a8b3f27f4b63");
System.out.println( "UUID from string with hyphens: " + uuidFromHyphens );

However, that UUID class fails with inputting a hex string without hyphens. This failure is unfortunate as the UUID spec does not require the hyphens in a hex string representation. This fails:

然而,UUID类在没有连字符的情况下输入十六进制字符串失败。这个失败是不幸的,因为UUID规范不需要十六进制字符串表示中的连字符。这个操作失败:

java.util.UUID uuidFromNoHyphens = java.util.UUID.fromString("6f34f25e0b0d44268ecea8b3f27f4b63");

Regex

One workaround is to format the hex string to add the canonical hyphens. Here's my attempt at using regex to format the hex string. Beware… This code works, but I'm no regex expert. You should make this code more robust, say checking that the length of the string is 32 characters before formatting and 36 after.

一个解决方案是格式化十六进制字符串以添加规范的连字符。下面是我使用regex格式化十六进制字符串的尝试。这段代码有效,但我不是regex专家。您应该使这个代码更加健壮,比如检查字符串的长度是32个字符,然后是格式化,然后是36个字符。

    // -----|  With Hyphens  |----------------------
java.util.UUID uuidFromHyphens = java.util.UUID.fromString( "6f34f25e-0b0d-4426-8ece-a8b3f27f4b63" );
System.out.println( "UUID from string with hyphens: " + uuidFromHyphens );
System.out.println();

// -----|  Without Hyphens  |----------------------
String hexStringWithoutHyphens = "6f34f25e0b0d44268ecea8b3f27f4b63";
// Use regex to format the hex string by inserting hyphens in the canonical format: 8-4-4-4-12
String hexStringWithInsertedHyphens =  hexStringWithoutHyphens.replaceFirst( "([0-9a-fA-F]{8})([0-9a-fA-F]{4})([0-9a-fA-F]{4})([0-9a-fA-F]{4})([0-9a-fA-F]+)", "$1-$2-$3-$4-$5" );
System.out.println( "hexStringWithInsertedHyphens: " + hexStringWithInsertedHyphens );
java.util.UUID myUuid = java.util.UUID.fromString( hexStringWithInsertedHyphens );
System.out.println( "myUuid: " + myUuid );

Posix Notation

You might find this alternative syntax more readable, using Posix notation within the regex where \\p{XDigit} takes the place of [0-9a-fA-F] (see Pattern doc):

您可能会发现这种替代语法更加可读,在regex中使用Posix标记,其中\\p{XDigit}取代[0-9a-fA-F](参见模式文档):

String hexStringWithInsertedHyphens =  hexStringWithoutHyphens.replaceFirst( "(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", "$1-$2-$3-$4-$5" );

Complete example.

完整的例子。

java.util.UUID uuid =
        java.util.UUID.fromString (
                "5231b533ba17478798a3f2df37de2aD7"
                        .replaceFirst (
                                "(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)",
                                "$1-$2-$3-$4-$5"
                        )
        );

System.out.println ( "uuid.toString(): " + uuid );

uuid.toString(): 5231b533-ba17-4787-98a3-f2df37de2ad7

uuid.toString():5231 b533 ba17 - 4787 - 98 - a3 - f2df37de2ad7

#3


9  

You could do a goofy regular expression replacement:

你可以做一个愚蠢的正则表达式替换:

String digits = "5231b533ba17478798a3f2df37de2aD7";                         
String uuid = digits.replaceAll(                                            
    "(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})",                            
    "$1-$2-$3-$4-$5");                                                      
System.out.println(uuid); // => 5231b533-ba17-4787-98a3-f2df37de2aD7

#4


5  

Regexp solution is probably faster, but you can also look at that :)

Regexp解决方案可能更快,但您也可以看一下:)

String withoutDashes = "44e128a5-ac7a-4c9a-be4c-224b6bf81b20".replaceAll("-", "");      
BigInteger bi1 = new BigInteger(withoutDashes.substring(0, 16), 16);                
BigInteger bi2 = new BigInteger(withoutDashes.substring(16, 32), 16);
UUID uuid = new UUID(bi1.longValue(), bi2.longValue());
String withDashes = uuid.toString();

By the way, conversion from 16 binary bytes to uuid

顺便说一下,从16个二进制字节转换为uuid。

  InputStream is = ..binarty input..;
  byte[] bytes = IOUtils.toByteArray(is);
  ByteBuffer bb = ByteBuffer.wrap(bytes);
  UUID uuidWithDashesObj = new UUID(bb.getLong(), bb.getLong());
  String uuidWithDashes = uuidWithDashesObj.toString();

#5


4  

A much (~ 900%) faster solution compared to using regexps and string manipulation is to just parse the hex string into 2 longs and create the UUID instance from those:

与使用regexp和字符串操作相比,一个更快速的解决方案是将十六进制字符串解析成两个longs,并从这些字符串中创建UUID实例:

(defn uuid-from-string
  "Converts a 32digit hex string into java.util.UUID"
  [hex]
  (java.util.UUID.
    (Long/parseUnsignedLong (subs hex 0 16) 16)
    (Long/parseUnsignedLong (subs hex 16) 16)))

#6


3  

public static String addUUIDDashes(String idNoDashes) {
    StringBuffer idBuff = new StringBuffer(idNoDashes);
    idBuff.insert(20, '-');
    idBuff.insert(16, '-');
    idBuff.insert(12, '-');
    idBuff.insert(8, '-');
    return idBuff.toString();
}

Maybe someone else can comment on the computational efficiency of this approach. (It wasn't a concern for my application.)

也许其他人可以评论这种方法的计算效率。(这不是我申请的问题。)

#7


3  

Optimized version of @maerics 's answer:

优化版@maerics的回答:

    String[] digitsList= {
            "daa70a7ffa904841bf9a81a67bdfdb45",
            "529737c950e6428f80c0bac104668b54",
            "5673c26e2e8f4c129906c74ec634b807",
            "dd5a5ee3a3c44e4fb53d2e947eceeda5",
            "faacc25d264d4e9498ade7a994dc612e",
            "9a1d322dc70349c996dc1d5b76b44a0a",
            "5fcfa683af5148a99c1bd900f57ea69c",
            "fd9eae8272394dfd8fd42d2bc2933579",
            "4b14d571dd4a4c9690796da318fc0c3a",
            "d0c88286f24147f4a5d38e6198ee2d18"
    };

    //Use compiled pattern to improve performance of bulk operations
    Pattern pattern = Pattern.compile("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})");

    for (int i = 0; i < digitsList.length; i++)
    {
        String uuid = pattern.matcher(digitsList[i]).replaceAll("$1-$2-$3-$4-$5");
        System.out.println(uuid);
    }

#8


1  

Another solution would be something similar to Pawel's solution but without creating new Strings and only solving the questions problem. If perfomance is a concern, avoid regex/split/replaceAll and UUID.fromString like the plague.

另一个解决方案类似于Pawel的解决方案,但不需要创建新的字符串,只解决问题。如果性能是一个问题,请避免使用regex/split/replaceAll和UUID.fromString like the plague。

String hyphenlessUuid = in.nextString();
BigInteger bigInteger = new BigInteger(hyphenlessUuid, 16);
 new UUID(bigInteger.shiftRight(64).longValue(), bigInteger.longValue());

#9


0  

I believe the following is the fastest in terms of performance. It is even slightly faster than Long.parseUnsignedLong version . It is slightly altered code that comes from java-uuid-generator.

我认为在性能方面,以下是最快的。它甚至比Long还要快。parseUnsignedLong版本。它是来自java-uuid-generator的稍微修改过的代码。

 public static UUID from32(
        String id) {
    if (id == null) {
        throw new NullPointerException();
    }
    if (id.length() != 32) {
        throw new NumberFormatException("UUID has to be 32 char with no hyphens");
    }

    long lo, hi;
    lo = hi = 0;

    for (int i = 0, j = 0; i < 32; ++j) {
        int curr;
        char c = id.charAt(i);

        if (c >= '0' && c <= '9') {
            curr = (c - '0');
        }
        else if (c >= 'a' && c <= 'f') {
            curr = (c - 'a' + 10);
        }
        else if (c >= 'A' && c <= 'F') {
            curr = (c - 'A' + 10);
        }
        else {
            throw new NumberFormatException(
                    "Non-hex character at #" + i + ": '" + c + "' (value 0x" + Integer.toHexString(c) + ")");
        }
        curr = (curr << 4);

        c = id.charAt(++i);

        if (c >= '0' && c <= '9') {
            curr |= (c - '0');
        }
        else if (c >= 'a' && c <= 'f') {
            curr |= (c - 'a' + 10);
        }
        else if (c >= 'A' && c <= 'F') {
            curr |= (c - 'A' + 10);
        }
        else {
            throw new NumberFormatException(
                    "Non-hex character at #" + i + ": '" + c + "' (value 0x" + Integer.toHexString(c) + ")");
        }
        if (j < 8) {
            hi = (hi << 8) | curr;
        }
        else {
            lo = (lo << 8) | curr;
        }
        ++i;
    }
    return new UUID(hi, lo);
}

#10


-1  

Maybe this:

也许是这样的:

String digits = "5231b533ba17478798a3f2df37de2aD7";                     
String.format("%s%s%s%s%s%s%s%s-%s%s%s%s-%s%s%s%s-%s%s%s%s-%s%s%s%s%s%s%s%s%s%s%s%s", digits.split(""));

#1


14  

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.)

Clojure的#uuid标记文字是对java.util.UUID/fromString的传递。并且,fromString将其拆分为“-”并将其转换为两个长值。(UUID的格式为8-4-4-4-12十六进制数字,但“-”实际上只用于验证和视觉识别。)

The straight forward solution is to reinsert the "-" and use java.util.UUID/fromString.

直接的解决方案是重新插入“-”并使用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.

如果您想要一些没有正则表达式的东西,可以使用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))))

#2


26  

tl;dr

java.util.UUID.fromString(
    "5231b533ba17478798a3f2df37de2aD7"
    .replaceFirst( 
        "(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", "$1-$2-$3-$4-$5" 
    )
).toString()

5231b533-ba17-4787-98a3-f2df37de2ad7

5231年b533 ba17 - 4787 - 98 - a3 - f2df37de2ad7

Bits, Not Text

A UUID is a 128-bit value. A UUID is not actually made up of letters and digits, it is made up of bits. You can think of it as describing a very, very large number.

UUID是128位的值。UUID实际上并不是由字母和数字组成的,而是由位组成的。你可以把它想象成一个非常非常大的数字。

We could display those bits as a one hundred and twenty eight 0 & 1 characters.

我们可以把这些位显示为一百二十八0和1个字符。

0111 0100 1101 0010 0101 0001 0101 0110 0110 0000 1110 0110 0100 0100 0100 1100 1010 0001 0111 0111 1010 1001 0110 1110 0110 0111 1110 1100 1111 1100 0101 1111

011101001101101101101001001001001100110011001100110011001100110011001101101011010110110110110110110110110110110110110110110110011001

Humans do not easily read bits, so for convenience we usually represent the 128-bit value as a hexadecimal string made up of letters and digits.

人类不容易读取比特,因此为了方便起见,我们通常将128位的值表示为由字母和数字组成的十六进制字符串。

74d25156-60e6-444c-a177-a96e67ecfc5f

74 d25156 - 60 - e6 - 444 c - a177 a96e67ecfc5f

Such a hex string is not the UUID itself, only a human-friendly representation. The hyphens are added per the UUID spec as canonical formatting, but are optional.

这样的十六进制字符串不是UUID本身,而是一种对人友好的表示。在UUID规范中添加连字符作为规范格式,但是是可选的。

74d2515660e6444ca177a96e67ecfc5f

74年d2515660e6444ca177a96e67ecfc5f

By the way, the UUID spec clearly states that lowercase letters must be used when generating the hex string while uppercase should be tolerated as input. Unfortunately, many implementations violate that lowercase-generation rule, including those from Apple, Microsoft, and others. See my blog post.

顺便说一下,UUID规范清楚地指出,在生成十六进制字符串时必须使用小写字母,而大写应该作为输入被容忍。不幸的是,许多实现违反了小写生成规则,包括来自苹果、微软和其他的规则。看我的博客。


The following refers to Java, not Clojure.

以下是Java,而不是Clojure。

In Java 7 (and earlier), you may use the java.util.UUID class to instantiate a UUID based on a hex string with hyphens as input. Example:

在Java 7(和更早的版本)中,您可以使用Java .util。UUID类以带有连字符的十六进制字符串为输入实例化UUID。例子:

java.util.UUID uuidFromHyphens = java.util.UUID.fromString("6f34f25e-0b0d-4426-8ece-a8b3f27f4b63");
System.out.println( "UUID from string with hyphens: " + uuidFromHyphens );

However, that UUID class fails with inputting a hex string without hyphens. This failure is unfortunate as the UUID spec does not require the hyphens in a hex string representation. This fails:

然而,UUID类在没有连字符的情况下输入十六进制字符串失败。这个失败是不幸的,因为UUID规范不需要十六进制字符串表示中的连字符。这个操作失败:

java.util.UUID uuidFromNoHyphens = java.util.UUID.fromString("6f34f25e0b0d44268ecea8b3f27f4b63");

Regex

One workaround is to format the hex string to add the canonical hyphens. Here's my attempt at using regex to format the hex string. Beware… This code works, but I'm no regex expert. You should make this code more robust, say checking that the length of the string is 32 characters before formatting and 36 after.

一个解决方案是格式化十六进制字符串以添加规范的连字符。下面是我使用regex格式化十六进制字符串的尝试。这段代码有效,但我不是regex专家。您应该使这个代码更加健壮,比如检查字符串的长度是32个字符,然后是格式化,然后是36个字符。

    // -----|  With Hyphens  |----------------------
java.util.UUID uuidFromHyphens = java.util.UUID.fromString( "6f34f25e-0b0d-4426-8ece-a8b3f27f4b63" );
System.out.println( "UUID from string with hyphens: " + uuidFromHyphens );
System.out.println();

// -----|  Without Hyphens  |----------------------
String hexStringWithoutHyphens = "6f34f25e0b0d44268ecea8b3f27f4b63";
// Use regex to format the hex string by inserting hyphens in the canonical format: 8-4-4-4-12
String hexStringWithInsertedHyphens =  hexStringWithoutHyphens.replaceFirst( "([0-9a-fA-F]{8})([0-9a-fA-F]{4})([0-9a-fA-F]{4})([0-9a-fA-F]{4})([0-9a-fA-F]+)", "$1-$2-$3-$4-$5" );
System.out.println( "hexStringWithInsertedHyphens: " + hexStringWithInsertedHyphens );
java.util.UUID myUuid = java.util.UUID.fromString( hexStringWithInsertedHyphens );
System.out.println( "myUuid: " + myUuid );

Posix Notation

You might find this alternative syntax more readable, using Posix notation within the regex where \\p{XDigit} takes the place of [0-9a-fA-F] (see Pattern doc):

您可能会发现这种替代语法更加可读,在regex中使用Posix标记,其中\\p{XDigit}取代[0-9a-fA-F](参见模式文档):

String hexStringWithInsertedHyphens =  hexStringWithoutHyphens.replaceFirst( "(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", "$1-$2-$3-$4-$5" );

Complete example.

完整的例子。

java.util.UUID uuid =
        java.util.UUID.fromString (
                "5231b533ba17478798a3f2df37de2aD7"
                        .replaceFirst (
                                "(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)",
                                "$1-$2-$3-$4-$5"
                        )
        );

System.out.println ( "uuid.toString(): " + uuid );

uuid.toString(): 5231b533-ba17-4787-98a3-f2df37de2ad7

uuid.toString():5231 b533 ba17 - 4787 - 98 - a3 - f2df37de2ad7

#3


9  

You could do a goofy regular expression replacement:

你可以做一个愚蠢的正则表达式替换:

String digits = "5231b533ba17478798a3f2df37de2aD7";                         
String uuid = digits.replaceAll(                                            
    "(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})",                            
    "$1-$2-$3-$4-$5");                                                      
System.out.println(uuid); // => 5231b533-ba17-4787-98a3-f2df37de2aD7

#4


5  

Regexp solution is probably faster, but you can also look at that :)

Regexp解决方案可能更快,但您也可以看一下:)

String withoutDashes = "44e128a5-ac7a-4c9a-be4c-224b6bf81b20".replaceAll("-", "");      
BigInteger bi1 = new BigInteger(withoutDashes.substring(0, 16), 16);                
BigInteger bi2 = new BigInteger(withoutDashes.substring(16, 32), 16);
UUID uuid = new UUID(bi1.longValue(), bi2.longValue());
String withDashes = uuid.toString();

By the way, conversion from 16 binary bytes to uuid

顺便说一下,从16个二进制字节转换为uuid。

  InputStream is = ..binarty input..;
  byte[] bytes = IOUtils.toByteArray(is);
  ByteBuffer bb = ByteBuffer.wrap(bytes);
  UUID uuidWithDashesObj = new UUID(bb.getLong(), bb.getLong());
  String uuidWithDashes = uuidWithDashesObj.toString();

#5


4  

A much (~ 900%) faster solution compared to using regexps and string manipulation is to just parse the hex string into 2 longs and create the UUID instance from those:

与使用regexp和字符串操作相比,一个更快速的解决方案是将十六进制字符串解析成两个longs,并从这些字符串中创建UUID实例:

(defn uuid-from-string
  "Converts a 32digit hex string into java.util.UUID"
  [hex]
  (java.util.UUID.
    (Long/parseUnsignedLong (subs hex 0 16) 16)
    (Long/parseUnsignedLong (subs hex 16) 16)))

#6


3  

public static String addUUIDDashes(String idNoDashes) {
    StringBuffer idBuff = new StringBuffer(idNoDashes);
    idBuff.insert(20, '-');
    idBuff.insert(16, '-');
    idBuff.insert(12, '-');
    idBuff.insert(8, '-');
    return idBuff.toString();
}

Maybe someone else can comment on the computational efficiency of this approach. (It wasn't a concern for my application.)

也许其他人可以评论这种方法的计算效率。(这不是我申请的问题。)

#7


3  

Optimized version of @maerics 's answer:

优化版@maerics的回答:

    String[] digitsList= {
            "daa70a7ffa904841bf9a81a67bdfdb45",
            "529737c950e6428f80c0bac104668b54",
            "5673c26e2e8f4c129906c74ec634b807",
            "dd5a5ee3a3c44e4fb53d2e947eceeda5",
            "faacc25d264d4e9498ade7a994dc612e",
            "9a1d322dc70349c996dc1d5b76b44a0a",
            "5fcfa683af5148a99c1bd900f57ea69c",
            "fd9eae8272394dfd8fd42d2bc2933579",
            "4b14d571dd4a4c9690796da318fc0c3a",
            "d0c88286f24147f4a5d38e6198ee2d18"
    };

    //Use compiled pattern to improve performance of bulk operations
    Pattern pattern = Pattern.compile("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})");

    for (int i = 0; i < digitsList.length; i++)
    {
        String uuid = pattern.matcher(digitsList[i]).replaceAll("$1-$2-$3-$4-$5");
        System.out.println(uuid);
    }

#8


1  

Another solution would be something similar to Pawel's solution but without creating new Strings and only solving the questions problem. If perfomance is a concern, avoid regex/split/replaceAll and UUID.fromString like the plague.

另一个解决方案类似于Pawel的解决方案,但不需要创建新的字符串,只解决问题。如果性能是一个问题,请避免使用regex/split/replaceAll和UUID.fromString like the plague。

String hyphenlessUuid = in.nextString();
BigInteger bigInteger = new BigInteger(hyphenlessUuid, 16);
 new UUID(bigInteger.shiftRight(64).longValue(), bigInteger.longValue());

#9


0  

I believe the following is the fastest in terms of performance. It is even slightly faster than Long.parseUnsignedLong version . It is slightly altered code that comes from java-uuid-generator.

我认为在性能方面,以下是最快的。它甚至比Long还要快。parseUnsignedLong版本。它是来自java-uuid-generator的稍微修改过的代码。

 public static UUID from32(
        String id) {
    if (id == null) {
        throw new NullPointerException();
    }
    if (id.length() != 32) {
        throw new NumberFormatException("UUID has to be 32 char with no hyphens");
    }

    long lo, hi;
    lo = hi = 0;

    for (int i = 0, j = 0; i < 32; ++j) {
        int curr;
        char c = id.charAt(i);

        if (c >= '0' && c <= '9') {
            curr = (c - '0');
        }
        else if (c >= 'a' && c <= 'f') {
            curr = (c - 'a' + 10);
        }
        else if (c >= 'A' && c <= 'F') {
            curr = (c - 'A' + 10);
        }
        else {
            throw new NumberFormatException(
                    "Non-hex character at #" + i + ": '" + c + "' (value 0x" + Integer.toHexString(c) + ")");
        }
        curr = (curr << 4);

        c = id.charAt(++i);

        if (c >= '0' && c <= '9') {
            curr |= (c - '0');
        }
        else if (c >= 'a' && c <= 'f') {
            curr |= (c - 'a' + 10);
        }
        else if (c >= 'A' && c <= 'F') {
            curr |= (c - 'A' + 10);
        }
        else {
            throw new NumberFormatException(
                    "Non-hex character at #" + i + ": '" + c + "' (value 0x" + Integer.toHexString(c) + ")");
        }
        if (j < 8) {
            hi = (hi << 8) | curr;
        }
        else {
            lo = (lo << 8) | curr;
        }
        ++i;
    }
    return new UUID(hi, lo);
}

#10


-1  

Maybe this:

也许是这样的:

String digits = "5231b533ba17478798a3f2df37de2aD7";                     
String.format("%s%s%s%s%s%s%s%s-%s%s%s%s-%s%s%s%s-%s%s%s%s-%s%s%s%s%s%s%s%s%s%s%s%s", digits.split(""));