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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With