Created
November 17, 2021 07:52
-
-
Save stevegt/20c56f97b767c67aa325d465befcf2d6 to your computer and use it in GitHub Desktop.
custom template functions with regex https://play.golang.org/p/NSA9sWyvdAd
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"os" | |
"regexp" | |
"strings" | |
"text/template" | |
) | |
// regexFindAllSubmatch returns all the matching groups | |
// [0] string matches the whole regex | |
// [1:] strings matches the n-th group | |
func regexFindAllSubmatch(regex string, s string) []string { | |
r := regexp.MustCompile(regex) | |
return r.FindStringSubmatch(s) | |
} | |
func main() { | |
// First we create a FuncMap with which to register the function. | |
funcMap := template.FuncMap{ | |
// The name "title" is what the function will be called in the template text. | |
"title": strings.Title, | |
"re1": regexFindAllSubmatch, | |
} | |
// A simple template definition to test our function. | |
// We print the input text several ways: | |
// - the original | |
// - title-cased | |
// - title-cased and then printed with %q | |
// - printed with %q and then title-cased. | |
const templateText = ` | |
Input: {{printf "%q" .}} | |
Output 0: {{title .}} | |
Output 1: {{title . | printf "%q"}} | |
Output 2: {{printf "%q" . | title}} | |
Output 3: {{ "peach" | re1 "p([a-z]+)ch" }} | |
Output 4: {{ . | re1 "([a-z]+)a(mm[a-z]+)" }} | |
` | |
// Create a template, add the function map, and parse the text. | |
tmpl, err := template.New("titleTest").Funcs(funcMap).Parse(templateText) | |
if err != nil { | |
log.Fatalf("parsing: %s", err) | |
} | |
// Run the template to verify the output. | |
err = tmpl.Execute(os.Stdout, "the go programming language") | |
if err != nil { | |
log.Fatalf("execution: %s", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment