英文:
How do I match exactly a partial string in regexp and ignore any characters before and after a pattern?
问题
我正在使用golang的正则表达式,并且我想从字符串中提取一个模式。
例如,我可以在字符串中有以下的键值对:
"name1=val1;name2=val2;needle=haystack;name3=val3"
我要找的是完全匹配字符串"needle=haystack",并且丢弃其他任何内容。
如果我能够得到的结果只是"haystack"就更好了。
我该如何在golang中使用正则表达式来实现这个呢?
英文:
I am using golang regexp and I want to extract a pattern in a string.
For example, I can have the following name value pairs in the string:
"name1=val1;name2=val2;needle=haystack;name3=val3"
I am looking for exactly the string "needle=haystack" and discard anything else.
It would be even better if I could just get the result to be exactly haystack.
How do I do this with regexp in golang?
答案1
得分: 2
我不完全清楚目标是什么。如果你总是在寻找"needle=haystack",你可以使用strings.Contains(str, "needle=haystack")。
如果你真的想要用正则表达式来做,那么代码应该是下面这样的。
package main
import (
"fmt"
"regexp"
)
func main() {
str := "name1=val1;name2=val2;needle=haystack;name3=val3"
r := regexp.MustCompile("needle=([a-z]+);")
found := r.FindString(str)
if found == "" {
fmt.Println("No match found")
return
}
fmt.Println(found) // needle=haystack;
submatches := r.FindStringSubmatch(str)
fmt.Println(submatches) // [needle=haystack; haystack]
if len(submatches) < 2 {
fmt.Println("No submatch found")
return
}
fmt.Println(submatches[1]) // haystack
}
希望对你有帮助!
英文:
I'm not entirely clear on what the goal is. If you're always looking for needle=haystack then you can use strings.Contains(str, "needle=haystack").
If you really want to do it with regexes then it would be something like the code below.
package main
import (
"fmt"
"regexp"
)
func main() {
str := "name1=val1;name2=val2;needle=haystack;name3=val3"
r := regexp.MustCompile("needle=([a-z]+);")
found := r.FindString(str)
if found == "" {
fmt.Println("No match found")
return
}
fmt.Println(found) // needle=haystack;
submatches := r.FindStringSubmatch(str)
fmt.Println(submatches) // [needle=haystack; haystack]
if len(submatches) < 2 {
fmt.Println("No submatch found")
return
}
fmt.Println(submatches[1]) // haystack
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论