我有以下代码:
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))
}
但是当我将fbd3036f-0f1c-4e98-b71c-d4cd61213f90
作为值传递时,我得到false
,而实际上它是UUID v4。
我做错了什么?
答案 0 :(得分:25)
试试......
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)
}
答案 1 :(得分:12)
正则表达式很贵。以下方法是~18x times faster而不是正则表达式。
使用类似https://godoc.org/github.com/google/uuid#Parse的内容。
<div>
<form name="payform" action="pay.html" method="POST">
<div>
<input id="customerName" name="firstname" ng-model="customerName" style="display:none"/>
<input style="display:none" id="txnid" name="txnid" ng-model="transactionid" />
<input type="submit" name="paybutton" id="payit" />
</div>
</form>
</div>
答案 2 :(得分:6)
您可以使用satori / go.uuid包来完成此任务:
import "github.com/satori/go.uuid"
func IsValidUUID(u string) bool {
_, err := uuid.FromString(u)
return err == nil
}
此包广泛用于UUID操作:https://github.com/satori/go.uuid
答案 3 :(得分:1)
如果您将其验证为结构的属性,可以直接从Go中获得一个很棒的golang库,称为验证器https://godoc.org/gopkg.in/go-playground/validator.v9,您可以使用该库通过提供的内置函数来验证嵌套结构的各种字段验证程序以及完整的自定义验证方法。您只需要在字段中添加适当的标签
import "gopkg.in/go-playground/validator.v9"
type myObject struct {
UID string `validate:"required,uuid4"`
}
func validate(obj *myObject) {
validate := validator.New()
err := validate.Struct(obj)
}
它提供结构化的字段错误和其他相关数据。