Golang: extract data with Regex

后端 未结 4 930
萌比男神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: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(`\$\{([^}]*)\}`)
    

提交回复
热议问题