You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.6 KiB

2 years ago
  1. package util
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "regexp"
  6. "strings"
  7. "time"
  8. )
  9. // 生成随机数字字符串
  10. func RandomNumberStr(length int) string {
  11. nums := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  12. r := len(nums)
  13. rand.Seed(time.Now().UnixNano())
  14. var sb strings.Builder
  15. for i := 0; i < length; i++ {
  16. // 短信验证码第一位不能是0
  17. if i == 0 {
  18. fmt.Fprintf(&sb, "%d", nums[1:r][rand.Intn(r-1)])
  19. } else {
  20. fmt.Fprintf(&sb, "%d", nums[rand.Intn(r)])
  21. }
  22. }
  23. return sb.String()
  24. }
  25. func RandStr(size int) string {
  26. src := []string{"1", "2", "3", "4", "5", "6", "7", "8", "8", "0",
  27. "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
  28. "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
  29. "y", "v", "w", "x", "y", "z",
  30. "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
  31. "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
  32. "Y", "V", "W", "X", "Y", "Z"}
  33. var res []string
  34. for i := 0; i < size; i++ {
  35. res = append(res, src[rand.Int31n(62)])
  36. }
  37. return strings.Join(res, "")
  38. }
  39. func NotEmpty(v interface{}) bool {
  40. return v != nil && v != ""
  41. }
  42. func CompressStr(str string) string {
  43. if str == "" {
  44. return ""
  45. }
  46. //匹配一个或多个空白符的正则表达式
  47. reg := regexp.MustCompile("\\s+")
  48. return reg.ReplaceAllString(str, "")
  49. }
  50. // 通过map主键唯一的特性过滤重复元素
  51. func RemoveRepByMap(slc []string) []string {
  52. result := []string{}
  53. tempMap := map[string]byte{} // 存放不重复主键
  54. for _, e := range slc {
  55. if e != "" {
  56. l := len(tempMap)
  57. tempMap[e] = 0
  58. if len(tempMap) != l { // 加入map后,map长度变化,则元素不重复
  59. result = append(result, e)
  60. }
  61. }
  62. }
  63. return result
  64. }