为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
www说 2022-01-10 17:17:31
我正在尝试提取其中的任何数据${}。例如,从这个字符串中提取的数据应该是abc.git commit -m '${abc}'这是实际的代码:re := regexp.MustCompile("${*}")match := re.FindStringSubmatch(command)但这不起作用,你知道吗?
查看完整描述

3 回答

?
RISEBY

TA贡献1856条经验 获得超5个赞

你需要 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(`\$\{([^}]*)\}`)


查看完整回答
反对 回复 2022-01-10
?
繁华开满天机

TA贡献1816条经验 获得超4个赞

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


查看完整回答
反对 回复 2022-01-10
?
慕标5832272

TA贡献1966条经验 获得超4个赞

你也可以试试这个


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


str := "git commit -m '${abc}'"

res := re.FindAllStringSubmatch(str, 1)

for i := range res {

    //like Java: match.group(1)

    fmt.Println("Message :", res[i][1])

}

GoPlay:https : //play.golang.org/p/PFH2oDzNIEi


查看完整回答
反对 回复 2022-01-10
  • 3 回答
  • 0 关注
  • 921 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号