当前位置: > > > > 如何匹配单词之间的短语
来源:stackoverflow
2024-04-21 13:27:35
0浏览
收藏
你在学习Golang相关的知识吗?本文《如何匹配单词之间的短语》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!
问题内容
我试图仅从下面的代码块中捕获用户上下文。简而言之,我想要 repo_ 和 _tag 之间的所有内容,请发送示例。
package main import ( "regexp" "fmt" ) func main() { var re = regexp.MustCompile(`repo_(.*)_tag`) var str = `#gitflow variable "repo_user-context_tag" { default = "blah" } #gitflow variable "repo_user-office_tag" { default = "blah" } ` for _, match := range re.FindAllString(str, -1) { fmt.Println(match) } }
输出: repo_user-context_tag repo_user-office_tag
解决方案
你的正则表达式没有任何问题。问题是您使用了错误的函数来查看您要查找的子字符串匹配。
您需要 ,而不是 findallstring
:
package main import ( "regexp" "fmt" ) func main() { var re = regexp.mustcompile(`repo_(.*)_tag`) var str = `#gitflow variable "repo_user-context_tag" { default = "blah" } #gitflow variable "repo_user-office_tag" { default = "blah" } ` for _, match := range re.findallstringsubmatch(str, -1) { fmt.println(match[1]) } }
查看。
输出:
user-context user-office
今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注公众号,一起学习编程~