github.com/coveo/gotemplate@v2.7.7+incompatible/utils/substitute.go (about) 1 package utils 2 3 import ( 4 "regexp" 5 "strings" 6 7 "github.com/coveo/gotemplate/errors" 8 ) 9 10 // RegexReplacer defines struct composed of one regular expression and its replacement string 11 type RegexReplacer struct { 12 regex *regexp.Regexp 13 replace string 14 } 15 16 // InitReplacers configures the list of substitution that should be applied on each document 17 func InitReplacers(replacers ...string) []RegexReplacer { 18 result := make([]RegexReplacer, len(replacers)) 19 for i := range replacers { 20 replacers[i] = strings.TrimSpace(replacers[i]) 21 if replacers[i] == "" { 22 errors.Raise("Bad replacer %s", replacers[i]) 23 } 24 expression := strings.Split(replacers[i], string(replacers[i][0])) 25 if len(expression) != 3 || expression[1] == "" { 26 errors.Raise("Bad replacer %s", replacers[i]) 27 } 28 29 if expression[2] == "d" { 30 // If the replace expression is a single d (as in delete), we replace the 31 // expression by nothing 32 if strings.HasSuffix(expression[1], "$") { 33 // If we really want to delete lines, we must add \n explicitly 34 expression[1] += `\n` 35 if !strings.HasPrefix(expression[1], "(?m)") { 36 // If the search expression doesn't enable multi line 37 // we enable it 38 expression[1] = "(?m)" + expression[1] 39 } 40 } 41 expression[2] = "" 42 } 43 result[i].regex = regexp.MustCompile(expression[1]) 44 result[i].replace = expression[2] 45 46 } 47 return result 48 } 49 50 // Substitute actually applies the configured substituter 51 func Substitute(content string, replacers ...RegexReplacer) string { 52 for i := range replacers { 53 content = replacers[i].regex.ReplaceAllString(content, replacers[i].replace) 54 } 55 return content 56 }