【发布时间】:2021-07-06 02:58:06
【问题描述】:
我有一个将 jpg 文件与正则表达式和 golang 匹配的示例。
它完美地选择了它,但与我想要的相反,它删除它而不是保留它。
我如何让它成为替代品,因为目前你会看到它删除了 jpg 链接,并将其余部分留在我想要的相反的地方,只留下 jpg 链接。
这用于 xpath 刮板,我希望它只通过 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?:\/\/\S*\.jpg).*
替换为$1。
请参阅regex demo。
详情:
.*? - 除换行符以外的任何零个或多个字符,尽可能少(https?://\S*\.jpg) - 第 1 组 ($1):http,可选的 s、://、零个或多个非空白字符,然后是 .jpg 子字符串.* - 除换行符以外的任何零个或多个字符,尽可能多【讨论】: