Last active
May 19, 2020 10:45
-
-
Save mahmoud-eskandari/37783e6320559f9d197f21c48ba10dcf to your computer and use it in GitHub Desktop.
Golang Simple Eval string
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
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 |
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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[key] condition [/key]
{key} print value