How to check UUID v4 in Go?

I have the following code snippet:

func GetUUIDValidator(text string) bool { r, _ := regexp.Compile("/[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}/") return r.Match([]byte(text)) } 

But when I pass fbd3036f-0f1c-4e98-b71c-d4cd61213f90 as a value, I got false , but really it is UUID v4.

What am I doing wrong?

+12
go
source share
3 answers

Try with ...

 func IsValidUUID(uuid string) bool { r := regexp.MustCompile("^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$") return r.MatchString(uuid) } 

Life example: https://play.golang.org/p/a4Z-Jn4EvG

Note: as others have said, validating UUIDs with regular expressions can be slow. Consider other options if you need better performance.

+27
source share

Regex is expensive. The following approach is ~ 18 times faster than the regular expression version.

Instead, use something like https://godoc.org/github.com/google/uuid#Parse .

 import "github.com/google/uuid" func IsValidUUID(u string) bool { _, err := uuid.Parse(u) return err == nil } 
+13
source share

You can use satori / go.uuid package for this:

 import "github.com/satori/go.uuid" func IsValidUUID(u string) bool { _, err := uuid.FromString(u) return err == nil } 

This package is widely used for UUID operations: https://github.com/satori/go.uuid

+7
source share

All Articles