从字符串中提取信息

https://website-name.some-domain.some-sub-domain.com/resourceId当给定(类型 1)或(类型 2)形式的字符串时https://website-name.some-sub-domain.com/resourceId?randomContent,我只需要提取两个子字符串。我需要website-name一个字符串和resourceId另一字符串。


我使用以下代码提取了网站名称:


s := "https://website-name.some-domain.some-sub-domain.com/resourceId?randomContent"

w := regexp.MustCompile("https://(.*?)\\.")

website := w.FindStringSubmatch(s)

fmt.Println(website[1])

我有其他正则表达式来获取resourceId


s := "https://website-name.some-domain.some-sub-domain.com/resourceId?randomContent"

r := regexp.MustCompile("com/(.*?)\\?")

resource := r.FindStringSubmatch(s)

fmt.Println(resource[1])

这适用于任何以?或结尾的字符串?randomContent。但我的字符串没有尾随?,我无法处理这种情况(类型 1)。


我试图"(com/(.*?)\\?)|(com/(.*?).*)"得到resourceId但没有用。


我无法找到一种优雅的方法来提取这两个子字符串。


注意:therandomContent是任意长的子串,the 也是如此resourceId。但里面resourceId不会有。?遇到a ?,就可以说resourceId结束了。


另外,website-name可以不同,但模式是相同的 - 任意子域和 a.com将出现在字符串中。


这是我尝试过的: https: //play.golang.org/p/MGQIT5XRuuh


一只斗牛犬
浏览 82回答 3
3回答

慕容3067478

您显示的示例字符串是普通的 HTTPS URL,因此您可以使用该net/url包来解析它们。是website-name的第一部分parsedUrl.Hostname(),resourceId是parsedUrl.Path较少的前导部分/。u, err := url.Parse(s)if err != nil {    panic(err)}host := u.Hostname()first := strings.SplitN(host, ".", 2)[0]fmt.Printf("website-name: %s\n", first)fmt.Printf("resourceId: %s\n", u.Path[1:])https://play.golang.org/p/fnF2RTBuFxR有一个完整的示例,包括问题中的两个 URL 字符串。即使 URL 的主机名部分不以 结尾.com,或者路径部分包含该字符串,或者存在端口号或哈希片段或其他变体,此方法也有效。

月关宝盒

我猜这个表达式可能有效:(?i)https?:\/\/(www\.)?([^.]*)[^\/]*\/([^?\r\n]*)测试package mainimport (    "regexp"    "fmt")func main() {    var re = regexp.MustCompile(`(?m)(?i)https?:\/\/(www\.)?([^.]*)[^\/]*\/([^?\r\n]*)`)    var str = `https://website-name.some-domain.some-sub-domain.com/resourceId?randomContenthttps://website-name.some-domain.some-sub-domain.com/resourceId`    for i, match := range re.FindAllString(str, -1) {        fmt.Println(match, "found at index", i)    }}演示

扬帆大鱼

也许像这样简单的事情会有帮助。您可以使用以下正则表达式提取网站名称并返回第一组://([^/.]+)//         start with //([^/.]+)   match anything until first dot您可以使用以下正则表达式提取resourceId并返回第一组:.com/([^/?]+).com/      start with .com([^/?]+)   match everything until the first ? (if exists, else matches till end)链接到 Go Playground
打开App,查看更多内容
随时随地看视频慕课网APP