github.com/hugorut/terraform@v1.1.3/src/lang/funcs/string.go (about) 1 package funcs 2 3 import ( 4 "regexp" 5 "strings" 6 7 "github.com/zclconf/go-cty/cty" 8 "github.com/zclconf/go-cty/cty/function" 9 ) 10 11 // ReplaceFunc constructs a function that searches a given string for another 12 // given substring, and replaces each occurence with a given replacement string. 13 var ReplaceFunc = function.New(&function.Spec{ 14 Params: []function.Parameter{ 15 { 16 Name: "str", 17 Type: cty.String, 18 }, 19 { 20 Name: "substr", 21 Type: cty.String, 22 }, 23 { 24 Name: "replace", 25 Type: cty.String, 26 }, 27 }, 28 Type: function.StaticReturnType(cty.String), 29 Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { 30 str := args[0].AsString() 31 substr := args[1].AsString() 32 replace := args[2].AsString() 33 34 // We search/replace using a regexp if the string is surrounded 35 // in forward slashes. 36 if len(substr) > 1 && substr[0] == '/' && substr[len(substr)-1] == '/' { 37 re, err := regexp.Compile(substr[1 : len(substr)-1]) 38 if err != nil { 39 return cty.UnknownVal(cty.String), err 40 } 41 42 return cty.StringVal(re.ReplaceAllString(str, replace)), nil 43 } 44 45 return cty.StringVal(strings.Replace(str, substr, replace, -1)), nil 46 }, 47 }) 48 49 // Replace searches a given string for another given substring, 50 // and replaces all occurences with a given replacement string. 51 func Replace(str, substr, replace cty.Value) (cty.Value, error) { 52 return ReplaceFunc.Call([]cty.Value{str, substr, replace}) 53 }