概述
下面的go包可以用来从一个给定的字符串中提取URL
有两种方法可以使用这个包
-
严格--在严格模式下,它只匹配有方案的URL。
-
放松- 在放松模式下,它匹配任何由严格模式匹配的URL和任何没有方案的URL。
你可以指定要过滤的方案。有一个函数可以实现这一点
StrictMatchingScheme
程序
让我们先看看一个程序
package main
import (
"fmt"
"mvdan.cc/xurls/v2"
)
func main() {
xurlsStrict := xurls.Strict()
output := xurlsStrict.FindAllString("golangbyexample.com is https://golangbyexample.com", -1)
fmt.Println(output)
xurlsRelaxed := xurls.Relaxed()
output = xurlsRelaxed.FindAllString("The website is golangbyexample.com", -1)
fmt.Println(output)
output = xurlsRelaxed.FindAllString("golangbyexample.com is https://golangbyexample.com", -1)
fmt.Println(output)
}
输出
[https://golangbyexample.com]
[golangbyexample.com]
[golangbyexample.com https://golangbyexample.com]
注意在严格模式下,它不会在输出中返回golangbyexample.com,因为它没有一个方案。
让我们看看另一个提取多个URL的程序
package main
import (
"fmt"
"mvdan.cc/xurls/v2"
)
func main() {
xurlsStrict := xurls.Strict()
input := "The webiste is https://golangbyexample.com:8000/tutorials/intro amd mail to mailto:contactus@golangbyexample.com"
output := xurlsStrict.FindAllString(input, -1)
fmt.Println(output)
}
输出
[https://golangbyexample.com:8000/tutorials/intro mailto:contactus@golangbyexample.com]
如果我们想把输出限制在一个特定的方案上,也可以这样做。
package main
import (
"fmt"
"log"
"mvdan.cc/xurls/v2"
)
func main() {
xurlsStrict, err := xurls.StrictMatchingScheme("https")
if err != nil {
log.Fatalf("Some error occured. Error: %s", err)
}
input := "The webiste is https://golangbyexample.com:8000/tutorials/intro amd mail to mailto:contactus@golangbyexample.com"
output := xurlsStrict.FindAllString(input, -1)
fmt.Println(output)
}
输出
[https://golangbyexample.com:8000/tutorials/intro]
在上面的程序中,我们提供的方案是https,这就是为什么我们只有一个输出。
The postExtract a URL from a string in Go (Golang)appeared first onWelcome To Golang By Example.