github.com/Anderson-Lu/gobox@v0.0.0-20191127065433-3e6c4c2da420/string/string_helper.go (about) 1 package string 2 3 import ( 4 "math/rand" 5 "regexp" 6 "time" 7 ) 8 9 var urlRegexp *regexp.Regexp 10 var src = rand.NewSource(time.Now().UnixNano()) 11 12 const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" 13 const ( 14 letterIdxBits = 6 // 6 bits to represent a letter index 15 letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits 16 letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits 17 ) 18 19 func init() { 20 urlRegexp = regexp.MustCompile(`(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]`) 21 } 22 23 /* 24 * Find urls from specific string 25 */ 26 func FindUrl(raw string) []string { 27 return urlRegexp.FindAllString(raw, -1) 28 } 29 30 /* 31 * Generate a random string 32 */ 33 func RandStringBytesMaskImprSrc(n int) string { 34 b := make([]byte, n) 35 // A src.Int63() generates 63 random bits, enough for letterIdxMax characters! 36 for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; { 37 if remain == 0 { 38 cache, remain = src.Int63(), letterIdxMax 39 } 40 if idx := int(cache & letterIdxMask); idx < len(letterBytes) { 41 b[i] = letterBytes[idx] 42 i-- 43 } 44 cache >>= letterIdxBits 45 remain-- 46 } 47 48 return string(b) 49 }