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

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
    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(`\$\{([^}]*)\}`)
    
    点赞 评论
  • donglang1894
    donglang1894 2016-05-19 07:42

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

    点赞 评论
  • douci2022
    douci2022 2016-05-19 07:43

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

相关推荐