Golang: extract data with Regex
In regex, $
, {
and }
have special meaning
$ <-- End of string
{} <-- Contains the range. e.g. a{1,2}
So you need to escape them in the regex. Because of things like this, it is best to use raw string literals when working with regular expressions:
re := regexp.MustCompile(`\$\{([^}]*)\}`)
match := re.FindStringSubmatch("git commit -m '${abc}'")
fmt.Println(match[1])
Golang Demo
With double quotes (interpreted string literals) you need to also escape the backslashes:
re := regexp.MustCompile("\\$\\{(.*?)\\}")
Try re := regexp.MustCompile(\$\{(.*)\})
* is a quantifier, you need something to quantify. .
would do as it matches everything.