You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
1.6 KiB
Go
64 lines
1.6 KiB
Go
1 year ago
|
// Package textutil provide some extra text handle util
|
||
|
package textutil
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"git.noahlan.cn/noahlan/ntool/narr"
|
||
|
"git.noahlan.cn/noahlan/ntool/nmap"
|
||
|
"git.noahlan.cn/noahlan/ntool/nstr"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
// ReplaceVars by regex replace given tpl vars.
|
||
|
//
|
||
|
// If format is empty, will use {const defaultVarFormat}
|
||
|
func ReplaceVars(text string, vars map[string]any, format string) string {
|
||
|
return NewVarReplacer(format).Replace(text, vars)
|
||
|
}
|
||
|
|
||
|
// RenderSMap by regex replace given tpl vars.
|
||
|
//
|
||
|
// If format is empty, will use {const defaultVarFormat}
|
||
|
func RenderSMap(text string, vars map[string]string, format string) string {
|
||
|
return NewVarReplacer(format).RenderSimple(text, vars)
|
||
|
}
|
||
|
|
||
|
// IsMatchAll keywords in the give text string.
|
||
|
//
|
||
|
// TIP: can use ^ for exclude match.
|
||
|
func IsMatchAll(s string, keywords []string) bool {
|
||
|
return nstr.SimpleMatch(s, keywords)
|
||
|
}
|
||
|
|
||
|
// ParseInlineINI parse config string to string-map. it's like INI format contents.
|
||
|
//
|
||
|
// Examples:
|
||
|
//
|
||
|
// eg: "name=val0;shorts=i;required=true;desc=a message"
|
||
|
// =>
|
||
|
// {name: val0, shorts: i, required: true, desc: a message}
|
||
|
func ParseInlineINI(tagVal string, keys ...string) (mp nmap.SMap, err error) {
|
||
|
ss := nstr.Split(tagVal, ";")
|
||
|
ln := len(ss)
|
||
|
if ln == 0 {
|
||
|
return
|
||
|
}
|
||
|
|
||
|
mp = make(nmap.SMap, ln)
|
||
|
for _, s := range ss {
|
||
|
if !strings.ContainsRune(s, '=') {
|
||
|
err = fmt.Errorf("parse inline config error: must match `KEY=VAL`")
|
||
|
return
|
||
|
}
|
||
|
|
||
|
key, val := nstr.TrimCut(s, "=")
|
||
|
if len(keys) > 0 && !narr.StringsHas(keys, key) {
|
||
|
err = fmt.Errorf("parse inline config error: invalid key name %q", key)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
mp[key] = val
|
||
|
}
|
||
|
return
|
||
|
}
|