如何在regexp中精确匹配部分字符串并忽略模式前后的任何字符?

时间:2016-12-10 20:42:02

标签: javascript regex go

我正在使用golang regexp,我想在字符串中提取一个模式。

例如,我可以在字符串中使用以下名称值对:

“NAME1 = VAL1; NAME2 = val2的;针=草堆; NAME3 = VAL3”

我正在寻找字符串“needle = haystack”并丢弃其他任何内容。

如果我能让结果完全是干草堆,那就更好了。

如何在golang中使用regexp执行此操作?

1 个答案:

答案 0 :(得分:1)

我并不完全清楚目标是什么。如果您一直在寻找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
}