Golang: extract data with Regex

后端 未结 4 922
萌比男神i
萌比男神i 2021-02-12 16:00

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

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

git commit -m          


        
相关标签:
4条回答
  • 2021-02-12 16:28

    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

    0 讨论(0)
  • 2021-02-12 16:31

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

    0 讨论(0)
  • 2021-02-12 16:35

    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(`\$\{([^}]*)\}`)
    
    0 讨论(0)
  • 2021-02-12 16:38

    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(`\$\{.+?)\}`)
    
    0 讨论(0)
提交回复
热议问题