使用正则表达式和golang选择jpg图像
我有一个将 jpg 文件与正则表达式和 golang 匹配的示例。
正则表达式示例
它完美地选择了它,但与我想要的相反,它删除了它而不是保留它。
我如何让它成为替代品,因为目前您会看到它删除了 jpg 链接,并将其余部分留在我想要的相反位置,只留下 jpg 链接。
这用于 xpath 抓取器中,我希望它仅传递 jpg 链接。
回答
您可以使用FindStringSubmatch[1]:
package main
import "regexp"
const (
s = "background-color:#000000; background-image:url(https://www.sample.com/free-videos/player-images/20170204-01.jpg); background-size: cover; position: relative;"
)
func main() {
a := regexp.MustCompile(`(([^)]+))`).FindStringSubmatch(s)
t := a[1]
println(t == "https://www.sample.com/free-videos/player-images/20170204-01.jpg")
}
但是,在实际代码中,请确保测试len(a). 这是一项非常常见的任务,因此如果您有兴趣,也可以使用模块xurls[2]。
- https://golang.org/pkg/regexp#Regexp.FindStringSubmatch
- https://pkg.go.dev/mvdan.cc/xurls/v2