猿问

Golang:使用正则表达式提取数据

我正在尝试提取其中的任何数据${}。


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


git commit -m '${abc}'

这是实际的代码:


re := regexp.MustCompile("${*}")

match := re.FindStringSubmatch(command)

但这不起作用,你知道吗?


www说
浏览 922回答 3
3回答

RISEBY

你需要 escape $,{并且}在正则表达式中。re := regexp.MustCompile("\\$\\{(.*?)\\}")match := re.FindStringSubmatch("git commit -m '${abc}'")fmt.Println(match[1])Golang 演示在正则表达式中,$ <-- End of string{} <-- Contains the range. e.g. a{1,2}你也可以使用re := regexp.MustCompile(`\$\{([^}]*)\}`)

繁华开满天机

试试 re :=&nbsp;regexp.MustCompile(\$\{(.*)\})&nbsp;* 是一个量词,你需要一些东西来量化。.会做,因为它匹配一切。

慕标5832272

你也可以试试这个re := regexp.MustCompile("\\$\\{(.*?)\\}")str := "git commit -m '${abc}'"res := re.FindAllStringSubmatch(str, 1)for i := range res {&nbsp; &nbsp; //like Java: match.group(1)&nbsp; &nbsp; fmt.Println("Message :", res[i][1])}GoPlay:https : //play.golang.org/p/PFH2oDzNIEi
随时随地看视频慕课网APP

相关分类

Go
我要回答