使用正则表达式和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]。

  1. https://golang.org/pkg/regexp#Regexp.FindStringSubmatch
  2. https://pkg.go.dev/mvdan.cc/xurls/v2

以上是使用正则表达式和golang选择jpg图像的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>