英文:
golang extract unique key, value from a key=value pair string using regex
问题
我有以下的Go字符串:
dbConnStr := "user=someone password=something host=superduperhost sslmode=something"
但是k=v对的顺序可能是任意的,例如:
dbConnStr := "host=superduperhost user=someone password=something"
请注意键的顺序的不同,以及字符串中缺少"sslmode"键。
另外,个别的k,v对可能用换行符分隔,而不是空格。
现在我想使用正则表达式从给定的字符串中提取唯一的键和它们对应的值。如果有帮助的话,我可以给出可能出现的所有键的列表(用户名、密码、主机、sslmode),但我更希望有一个可以适用于任何键和值列表的正则表达式解决方案。
如何做到这一点?我知道可以使用regexp.FindStringSubmatch,但是不知道如何编写正则表达式。
英文:
I have the following go string:
dbConnStr := "user=someone password=something host=superduperhost sslmode=something"
but the k=v pair code may be in any order, for example:
dbConnStr := "host=superduperhost user=someone password=something"
Notice the difference in the key order and also the missing "sslmode" key in the str.
Also, it is possible that instead of whitespace, the individual k,v pairs may be separated by newline too.
Now I want to extract the unique keys and their corresponding values from the given string, using regexp. If it will help, I can give a list of all the possible keys that may come (username, password, host, sslmode), but I would ideally like a regex solution that works with any list of keys and values.
How to do this ? I understand that it may be possible with regexp.FindStringSubmatch but not able to wrap my head around writing the regexp.
答案1
得分: 2
从golang nuts组获得了对此问题的答案。
var rex = regexp.MustCompile("(\\w+)=(\\w+)")
conn := `user=someone password=something host=superduperhost
sslmode=something`
data := rex.FindAllStringSubmatch(conn, -1)
res := make(map[string]string)
for _, kv := range data {
k := kv[1]
v := kv[2]
res[k] = v
}
fmt.Println(res)
Golang Playground链接:https://play.golang.org/p/xSEX1CAcQE
英文:
Got answer to this from golang nuts group.
var rex = regexp.MustCompile("(\\w+)=(\\w+)")
conn := `user=someone password=something host=superduperhost
sslmode=something`
data := rex.FindAllStringSubmatch(conn, -1)
res := make(map[string]string)
for _, kv := range data {
k := kv[1]
v := kv[2]
res[k] = v
}
fmt.Println(res)
Golang Playground url: https://play.golang.org/p/xSEX1CAcQE
答案2
得分: 0
以下是要翻译的内容:
个人而言,我会看一下这样的东西:
((user|password|host)=([\w]+)
这样你就可以在\1中得到键,\2中得到值。
在playground上的示例:
https://play.golang.org/p/6-Ler6-MrY
英文:
Personally I would look at something like:
((user|password|host)=([\w]+)
giving you key in \1 and value in \2.
Example on playground:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论