1
0
Fork 0
mirror of https://github.com/alice-lg/birdwatcher.git synced 2025-03-09 00:00:05 +01:00

added template expand helper

This commit is contained in:
Matthias Hannig 2017-07-14 15:42:45 +02:00
parent fa5b640aab
commit ebc9177c86
2 changed files with 46 additions and 0 deletions

20
bird/utils.go Normal file
View file

@ -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)
}

26
bird/utils_test.go Normal file
View file

@ -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)
}
}