duanliang4009 2016-05-19 07:37
浏览 106
已采纳

Golang:使用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?

  • 写回答

3条回答 默认 最新

  • dongpan1871 2016-05-19 07:44
    关注

    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(`\$\{([^}]*)\}`)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?