Golang:使用Regex提取数据

Ale*_*. b 15 regex string algorithm go

我正在尝试提取内部的任何数据${}.

例如,从该字符串中提取的数据应该是abc.

git commit -m '${abc}'
Run Code Online (Sandbox Code Playgroud)

这是实际的代码:

re := regexp.MustCompile("${*}")
match := re.FindStringSubmatch(command)
Run Code Online (Sandbox Code Playgroud)

但这不起作用,任何想法?

roc*_*987 29

你需要逃避$,{}在正则表达式.

re := regexp.MustCompile("\\$\\{(.*?)\\}")
match := re.FindStringSubmatch("git commit -m '${abc}'")
fmt.Println(match[1])
Run Code Online (Sandbox Code Playgroud)

Golang演示

在正则表达式中,

$ <-- End of string
{} <-- Contains the range. e.g. a{1,2}
Run Code Online (Sandbox Code Playgroud)

你也可以使用

re := regexp.MustCompile(`\$\{([^}]*)\}`)
Run Code Online (Sandbox Code Playgroud)

  • 提示:建议使用原始字符串文字来定义正则表达式模式.例如[`re:= regexp.MustCompile(\`\ $\{(.*?)\} \`)`](https://play.golang.org/p/jK5TSUGCxt) (7认同)