Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: extract data with 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?

like image 620
Alex. b Avatar asked May 19 '16 07:05

Alex. b


2 Answers

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("\\$\\{(.*?)\\}")
like image 91
rock321987 Avatar answered Oct 11 '22 22:10

rock321987


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

like image 43
Hermes Martinez Avatar answered Oct 12 '22 00:10

Hermes Martinez