diff --git a/bird/utils.go b/bird/utils.go new file mode 100644 index 0000000..a1cecea --- /dev/null +++ b/bird/utils.go @@ -0,0 +1,20 @@ +package bird + +import ( + "regexp" +) + +/* + Template Replace: + See https://golang.org/pkg/regexp/#Regexp.Expand + for a template reference. +*/ +func TemplateExpand(expr, template, input string) string { + reg := regexp.MustCompile(expr) + match := reg.FindStringSubmatchIndex(input) + + dst := []byte{} + res := reg.ExpandString(dst, template, input, match) + + return string(res) +} diff --git a/bird/utils_test.go b/bird/utils_test.go new file mode 100644 index 0000000..7c74713 --- /dev/null +++ b/bird/utils_test.go @@ -0,0 +1,26 @@ +package bird + +import ( + "testing" +) + +func TestTemplateExpand(t *testing.T) { + // Expect input to be something like + // TEST_FOO_42_src + // + // Template: + // RESULT_$1 + // + // Result: + // RESULT_FOO_42 + // + src := "TEST_FOO_42_src" + expr := `TEST_(.*)_src` + tmpl := "RESULT_${1}_${1}" + + res := TemplateExpand(expr, tmpl, src) + + if res != "RESULT_FOO_42_FOO_42" { + t.Error("Unexpacted expansion:", res) + } +}