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}'")

Golang Demo

With double quotes (interpreted string literals) you need to also escape the backslashes:

re := regexp.MustCompile("\\$\\{(.*?)\\}")

Leave a Comment