Skip to content

Instantly share code, notes, and snippets.

@mahmoud-eskandari
Last active May 19, 2020 10:45
Show Gist options
  • Save mahmoud-eskandari/37783e6320559f9d197f21c48ba10dcf to your computer and use it in GitHub Desktop.
Save mahmoud-eskandari/37783e6320559f9d197f21c48ba10dcf to your computer and use it in GitHub Desktop.
Golang Simple Eval string
EvalStr("[a]Hello is not empty![/a] Print: {a} {b} [c]Hidden c[/c] [c][a] c and a [/a][/c] [b][a] b and a [/a][/b]",map[string]string{"a":"Hello","b":"World","c":""})
// out: Hello is not empty! Print: Hello World b and a
func EvalStr(str string, input map[string]string) string {
for key := range input {
re := regexp.MustCompile(`(?mU)\[` + key + `\](.*)\[/` + key + `\]`)
for _, match := range re.FindAllString(str, -1) {
if len(input[key]) > 0 {
inner := strings.Replace(match, `[`+key+`]`, "", -1)
inner = strings.Replace(inner, `[/`+key+`]`, "", -1)
str = strings.Replace(str, match, inner, -1)
} else {
str = strings.Replace(str, match, "", 1)
}
}
str = strings.Replace(str, "{"+key+"}", input[key], -1)
}
// Replace not defined
re := regexp.MustCompile(`(?m)\[(.*?)\](.*)\[/(.*?)\]`)
for _, match := range re.FindAllString(str, -1) {
str = strings.Replace(str, match, "", 1)
}
re = regexp.MustCompile(`(?mU)\{(.*?)\}`)
for _, match := range re.FindAllString(str, -1) {
str = strings.Replace(str, match, "", 1)
}
return str
}
@mahmoud-eskandari
Copy link
Author

[key] condition [/key]

{key} print value

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment