登录
首页 >  Golang >  Go问答

找到正好匹配搜索条件的请求并停止搜索其他结果

来源:stackoverflow

时间:2024-03-02 18:00:28 128浏览 收藏

大家好,我们又见面了啊~本文《找到正好匹配搜索条件的请求并停止搜索其他结果》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

如果不使用正则表达式环顾四周(go 不支持),我如何匹配开始和结束字符而不从其他搜索中获取它们。

例如:想要匹配任何带有空格、逗号或分号以及开头和结尾的“dog”或“cat”。

所以:“dogdog,catcats;”将匹配“dog”,“dog”,“cat”。到目前为止,我所拥有的 (?:[ ,;]|^)(cat|dog)(?:[ ,;]|$) 将返回“dog”“cat”,因为匹配之间占用了空格


解决方案


我确实只看到了使用 go 实现此目的的几种方法。

最简单的方法是仅匹配一侧,然后执行一些后正则表达式逻辑:

https://play.golang.org/p/1_4fi-4kMhi

content := []byte("dog dog, cat cats; ")
re := regexp.mustcompile(`(?:[ ,;]|^)(cat|dog)`)
matches := re.findallindex(content, -1)
for _, match := range matches {
    next := string(content[match[1]])
    if next == "," || next == " " || next == ";" {
        fmt.println(string(content[match[0]:match[1]+1]))
    }
}

另一种方法是复制任何分隔符:

https://play.golang.org/p/krDlmHfepA1

content := []byte("dog dog, cat cats; ")
re := regexp.MustCompile(`([ ,;])`)
content = re.ReplaceAll(content, []byte("$1$1"))
fmt.Println(string(content))
re = regexp.MustCompile(`(?:[ ,;]|^)(cat|dog)(?:[ ,;]|$)`)
matches := re.FindAllSubmatch(content, -1)
for _, match := range matches {
    for _, submatch := range match[1:] {
        fmt.Println(string(submatch))    
    }
}

终于介绍完啦!小伙伴们,这篇关于《找到正好匹配搜索条件的请求并停止搜索其他结果》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>