Alex. b
Alex. b

Reputation: 689

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?

Upvotes: 36

Views: 66666

Answers (6)

Michaël COLL
Michaël COLL

Reputation: 1307

You can use named group to extract the value of a string.

import (
    "fmt"
    "regexp"
)

func main() {
    command := "git commit -m '${abc}'"

    r := regexp.MustCompile(`\$\{(?P<text>\w+)\}`)
    subMatch := r.FindStringSubmatch(command)

    fmt.Printf("text : %s", subMatch[1])
}

GoPlay

Upvotes: 1

rock321987
rock321987

Reputation: 11042

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("\\$\\{(.*?)\\}")

Upvotes: 58

Zombo
Zombo

Reputation: 1

For another approach, you can use os.Expand:

package main
import "os"

func main() {
   command := "git commit -m '${abc}'"
   var match string
   os.Expand(command, func(s string) string {
      match = s
      return ""
   })
   println(match == "abc")
}

https://golang.org/pkg/os#Expand

Upvotes: 1

ULLAS K
ULLAS K

Reputation: 901

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

Upvotes: 2

hobbs
hobbs

Reputation: 240819

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(`\$\{.+?)\}`)

Upvotes: 0

Hermes Martinez
Hermes Martinez

Reputation: 90

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

Upvotes: 4

Related Questions