util.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package util
  2. import (
  3. "math/rand"
  4. "regexp"
  5. "time"
  6. )
  7. const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  8. const (
  9. letterIdxBits = 6 // 6 bits to represent a letter index
  10. letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
  11. letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
  12. )
  13. func RandString(n int) string {
  14. result := make([]byte, n)
  15. // A rand.Int63() generates 63 random bits, enough for letterIdxMax characters!
  16. rand.Seed(time.Now().UnixNano())
  17. for i, cache, remain := n-1, rand.Int63(), letterIdxMax; i >= 0; {
  18. if remain == 0 {
  19. cache, remain = rand.Int63(), letterIdxMax
  20. }
  21. if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
  22. result[i] = letterBytes[idx]
  23. i--
  24. }
  25. cache >>= letterIdxBits
  26. remain--
  27. }
  28. return string(result)
  29. }
  30. // MsgFormat 格式化消息字符串 字符串里面有多个冒号,仅删除冒号前后的空格(如果存在)
  31. func MsgFormat(input string) string {
  32. // 定义正则表达式,用于匹配冒号两边的空格
  33. re := regexp.MustCompile(`\s*:\s*`)
  34. // 使用正则表达式替换所有匹配的部分
  35. return re.ReplaceAllString(input, ":")
  36. }