Golang:使用Regex提取数据

I'm trying to extract whatever data inside ${}.

For example, the data extracted from this string should be abc.

git commit -m '${abc}'

Here is the actual code:

re := regexp.MustCompile("${*}")
match := re.FindStringSubmatch(command)

But that doesn't work, any idea?

You need to escape $, { and } in the regex.

re := regexp.MustCompile("\\$\\{(.*?)\\}")
match := re.FindStringSubmatch("git commit -m '${abc}'")
fmt.Println(match[1])

Golang Demo

In regex,

$ <-- End of string
{} <-- Contains the range. e.g. a{1,2}

You can also use

re := regexp.MustCompile(`\$\{([^}]*)\}`)

Try re := regexp.MustCompile(\$\{(.*)\}) * is a quantifier, you need something to quantify. . would do as it matches everything.

Because $, { and } all have special meaning in a regex and need to be backslashed to match those literal characters, because * doesn't work that way, and because you didn't actually include a capturing group for the data you want to capture. Try:

re := regexp.MustCompile(`\$\{.+?)\}`)