Golang:使用Regex提取数据 [英] Golang: extract data with Regex

查看:191
本文介绍了Golang:使用Regex提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to extract whatever data inside ${}.

例如,提取的数据来自此字符串的应为 abc

For example, the data extracted from this string should be abc.

git commit -m '${abc}'

这是实际代码:

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

但这不起作用,有什么想法吗?

But that doesn't work, any idea?

推荐答案

您需要转义 $ {}

You need to escape $, { and } in the regex.

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

Golang演示

Golang Demo

在正则表达式中,

$ <-- End of string
{} <-- Contains the range. e.g. a{1,2}

您也可以使用

re := regexp.MustCompile(`\$\{([^}]*)\}`)

这篇关于Golang:使用Regex提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆