当前位置: > > > > 如何从url中检查并提取单词
如何从url中检查并提取单词
来源:stackoverflow
2024-04-29 16:54:34
0浏览
收藏
在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天米云就整理分享《如何从url中检查并提取单词》,聊聊,希望可以帮助到正在努力赚钱的你。
问题内容
go 内置正则表达式 pkg 的文档位于:https://golang.org/pkg/regexp/ go 中的正则表达式测试器位于此处:https://regoio.herokuapp.com
我有一个预定义单词列表:
christmas, santa, tree ( -> the order here is important. check for words from left to right)
我正在尝试检查不同网址字符串中的上述单词之一:
/api/container/:containerid/santa ( -> i want back santa) /api/tree/:containerid/ ( -> i want back tree) /api/tree/:containerid/christmas ( -> i want back christmas, not tree)
我尝试过的正则表达式是:
re := regexp.mustcompile(`^(christmas)|(santa)|(tree)$`)
fmt.println("santa? ", string(re.find([]byte(`/api/container/:containerid/santa`))))
// output ok: santa? santa
fmt.println("tree? ", string(re.find([]byte(`/api/tree/:containerid/`))))
// output fail/empty: tree?
fmt.println("christmas? ", string(re.find([]byte(`/api/tree/:containerid/christmas`))))
// output fail/empty: christmas?
还尝试了以下方法,但这返回了空字符串,而不是我正在查找的单词:
re := regexp.MustCompile(`^.*(christmas).*|.*(santa).*|.*(tree).*$`
fmt.Println("santa? ", string(re.Find([]byte(`/api/container/:containerID/santa`))))
// output FAIL/HOLE URL BACK: santa? /api/container/:containerID/santa
fmt.Println("tree? ", string(re.Find([]byte(`/api/tree/:containerID/`))))
// output FAIL/FAIL/HOLE URL BACK: tree? /api/tree/:containerID/
string(re.Find([]byte(`/api/tree/:containerID/christmas`))))
// output FAIL/FAIL/HOLE URL BACK: christmas? /api/tree/:containerID/christmas
我不知道正则表达式“引擎”的最后一个表达式有什么问题,应该只记住括号内的内容。
解决方案
不要使用正则表达式来执行此任务。它过于复杂,难以推理(正如您现在亲眼所见的那样),而且速度很慢。一种更简单的方法是简单地循环每个路径段并查找匹配项:
needles := []string{"christmas", "santa", "tree"}
sampleurl := `/api/container/:containerid/santa`
for _, part := range strings.split(sampleurl, "/") {
for _, needle := range needles {
if part == needle {
fmt.printf("found %s\n", needle)
}
}
}
如果您要搜索的单词很多,使用地图可能会提高效率:
needles := []string{"christmas", "santa", "tree", "reindeer", "bells", "chior", /* and possibly hundreds more */ }
needleMap := make(map[string]struct{}, len(needles))
for _, needle := range needles {
needleMap[needle] = struct{}{}
}
sampleURL := `/api/container/:containerID/santa`
for _, part := range strings.Split(sampleURL, "/") {
if _, ok := needleMap[part]; ok {
fmt.Printf("found %s\n", needle)
}
}
以上就是《如何从url中检查并提取单词》的详细内容,更多关于的资料请关注米云公众号!
