common.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "fmt"
  5. "regexp"
  6. "strings"
  7. )
  8. // MD5 字符串MD5加密
  9. func MD5(s string) string {
  10. data := []byte(s)
  11. has := md5.Sum(data)
  12. return fmt.Sprintf("%x", has)
  13. }
  14. // IsEmail 验证邮箱格式
  15. func IsEmail(email string) bool {
  16. pattern := `^[0-9a-z][_.0-9a-z-]{0,31}@([0-9a-z][0-9a-z-]{0,30}[0-9a-z]\.){1,4}[a-z]{2,4}$`
  17. reg := regexp.MustCompile(pattern)
  18. return reg.MatchString(email)
  19. }
  20. // IsMobile 验证手机号格式
  21. func IsMobile(mobile string) bool {
  22. pattern := `^1[3-9]\d{9}$`
  23. reg := regexp.MustCompile(pattern)
  24. return reg.MatchString(mobile)
  25. }
  26. // RemoveSpaces 去除字符串中的空格
  27. func RemoveSpaces(s string) string {
  28. return strings.ReplaceAll(s, " ", "")
  29. }
  30. // Substr 字符串截取
  31. func Substr(s string, start, length int) string {
  32. runes := []rune(s)
  33. total := len(runes)
  34. if start >= total {
  35. return ""
  36. }
  37. end := start + length
  38. if end > total {
  39. end = total
  40. }
  41. return string(runes[start:end])
  42. }
  43. func SplitAndFetch(s, sep string, index int) string {
  44. arr := strings.Split(s, sep)
  45. if index >= len(arr) {
  46. return ""
  47. }
  48. return arr[index]
  49. }