1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-07 22:22:29 +08:00

feat: add new functions in datetime and strutils

This commit is contained in:
dudaodong
2024-09-09 14:33:15 +08:00
parent cb7ff904d9
commit 2145808268
10 changed files with 650 additions and 1 deletions

View File

@@ -642,3 +642,32 @@ func Rotate(str string, shift int) string {
return sb.String()
}
// TemplateReplace replaces the placeholders in the template string with the corresponding values in the data map.
// The placeholders are enclosed in curly braces, e.g. {key}.
// for example, the template string is "Hello, {name}!", and the data map is {"name": "world"},
// the result will be "Hello, world!".
func TemplateReplace(template string, data map[string]string) string {
re := regexp.MustCompile(`\{(\w+)\}`)
result := re.ReplaceAllStringFunc(template, func(s string) string {
key := strings.Trim(s, "{}")
if val, ok := data[key]; ok {
return val
}
return s
})
result = strings.ReplaceAll(result, "{{", "{")
result = strings.ReplaceAll(result, "}}", "}")
return result
}
// RegexMatchAllGroups Matches all subgroups in a string using a regular expression and returns the result.
func RegexMatchAllGroups(pattern, str string) [][]string {
re := regexp.MustCompile(pattern)
matches := re.FindAllStringSubmatch(str, -1)
return matches
}