I\'m trying to extract whatever data inside ${}
.
For example, the data extracted from this string should be abc
.
git commit -m
You can try with this too,
re := regexp.MustCompile("\\$\\{(.*?)\\}")
str := "git commit -m '${abc}'"
res := re.FindAllStringSubmatch(str, 1)
for i := range res {
//like Java: match.group(1)
fmt.Println("Message :", res[i][1])
}
GoPlay: https://play.golang.org/p/PFH2oDzNIEi
Try re := regexp.MustCompile(\$\{(.*)\})
* is a quantifier, you need something to quantify. .
would do as it matches everything.
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(`\$\{([^}]*)\}`)
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(`\$\{.+?)\}`)