How do I match exactly a partial string in regexp and ignore any characters before and after a pattern?

huangapple go评论80阅读模式
英文:

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 (
    &quot;fmt&quot;
	&quot;regexp&quot;
)

func main() {
	str := &quot;name1=val1;name2=val2;needle=haystack;name3=val3&quot;

	r := regexp.MustCompile(&quot;needle=([a-z]+);&quot;)
	found := r.FindString(str)
    if found == &quot;&quot; {
    	fmt.Println(&quot;No match found&quot;)
	    return
	}
    fmt.Println(found) // needle=haystack;

	submatches := r.FindStringSubmatch(str)
	fmt.Println(submatches) // [needle=haystack; haystack]
    if len(submatches) &lt; 2 {
		fmt.Println(&quot;No submatch found&quot;)
	    return
    }
	fmt.Println(submatches[1]) // haystack
}

huangapple
  • 本文由 发表于 2016年12月11日 04:42:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/41080116.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定