1234567891011121314151617181920212223242526272829303132333435363738394041 |
- package util
- import (
- "math/rand"
- "regexp"
- "time"
- )
- const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
- const (
- letterIdxBits = 6 // 6 bits to represent a letter index
- letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
- letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
- )
- func RandString(n int) string {
- result := make([]byte, n)
- // A rand.Int63() generates 63 random bits, enough for letterIdxMax characters!
- rand.Seed(time.Now().UnixNano())
- for i, cache, remain := n-1, rand.Int63(), letterIdxMax; i >= 0; {
- if remain == 0 {
- cache, remain = rand.Int63(), letterIdxMax
- }
- if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
- result[i] = letterBytes[idx]
- i--
- }
- cache >>= letterIdxBits
- remain--
- }
- return string(result)
- }
- // MsgFormat 格式化消息字符串 字符串里面有多个冒号,仅删除冒号前后的空格(如果存在)
- func MsgFormat(input string) string {
- // 定义正则表达式,用于匹配冒号两边的空格
- re := regexp.MustCompile(`\s*:\s*`)
- // 使用正则表达式替换所有匹配的部分
- return re.ReplaceAllString(input, ":")
- }
|