regex.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package sprig
  2. import (
  3. "regexp"
  4. )
  5. func regexMatch(regex string, s string) bool {
  6. match, _ := regexp.MatchString(regex, s)
  7. return match
  8. }
  9. func mustRegexMatch(regex string, s string) (bool, error) {
  10. return regexp.MatchString(regex, s)
  11. }
  12. func regexFindAll(regex string, s string, n int) []string {
  13. r := regexp.MustCompile(regex)
  14. return r.FindAllString(s, n)
  15. }
  16. func mustRegexFindAll(regex string, s string, n int) ([]string, error) {
  17. r, err := regexp.Compile(regex)
  18. if err != nil {
  19. return []string{}, err
  20. }
  21. return r.FindAllString(s, n), nil
  22. }
  23. func regexFind(regex string, s string) string {
  24. r := regexp.MustCompile(regex)
  25. return r.FindString(s)
  26. }
  27. func mustRegexFind(regex string, s string) (string, error) {
  28. r, err := regexp.Compile(regex)
  29. if err != nil {
  30. return "", err
  31. }
  32. return r.FindString(s), nil
  33. }
  34. func regexReplaceAll(regex string, s string, repl string) string {
  35. r := regexp.MustCompile(regex)
  36. return r.ReplaceAllString(s, repl)
  37. }
  38. func mustRegexReplaceAll(regex string, s string, repl string) (string, error) {
  39. r, err := regexp.Compile(regex)
  40. if err != nil {
  41. return "", err
  42. }
  43. return r.ReplaceAllString(s, repl), nil
  44. }
  45. func regexReplaceAllLiteral(regex string, s string, repl string) string {
  46. r := regexp.MustCompile(regex)
  47. return r.ReplaceAllLiteralString(s, repl)
  48. }
  49. func mustRegexReplaceAllLiteral(regex string, s string, repl string) (string, error) {
  50. r, err := regexp.Compile(regex)
  51. if err != nil {
  52. return "", err
  53. }
  54. return r.ReplaceAllLiteralString(s, repl), nil
  55. }
  56. func regexSplit(regex string, s string, n int) []string {
  57. r := regexp.MustCompile(regex)
  58. return r.Split(s, n)
  59. }
  60. func mustRegexSplit(regex string, s string, n int) ([]string, error) {
  61. r, err := regexp.Compile(regex)
  62. if err != nil {
  63. return []string{}, err
  64. }
  65. return r.Split(s, n), nil
  66. }
  67. func regexQuoteMeta(s string) string {
  68. return regexp.QuoteMeta(s)
  69. }