Golang 截取 URL 字符串 - 如何获取 "html" 之后的第一个 & 前面的内容
您可以使用字符串操作函数和正则表达式来截取字符串。\n\n首先,您可以使用strings.Index函数找到"html"的索引位置。然后,使用字符串切片操作获取该索引之后的子字符串。最后,使用正则表达式来匹配第一个"\u0026"之前的内容。\n\n下面是一个示例代码:\n\ngo\npackage main\n\nimport (\n "fmt"\n "regexp"\n "strings"\n)\n\nfunc main() {\n url := "https://game.weixin.qq.com/cgi-bin/h5/static/appcenter/act_special.html?clusterid=10000036\u0026wechat_pkgid=appcenter_act_special\u0026ssid=3150\u0026immersivePageBgIsDark=0\u0026wechat_immersive=1\u0026immersiveUIStyle=1\u0026pre_inject_data=%5Bobject+Object%5D\u0026preInjectData=%5Bobject+Object%5D\u0026abt=64\u0026rpt_allpath=16304_999999_3150_999999_3150_8812_2881_8812_3154_2890_3150\u0026from_wechat_pkgid=pureprofile_index"\n\n // 查找"html"的索引位置\n index := strings.Index(url, "html")\n if index == -1 {\n fmt.Println("未找到"html"")\n return\n }\n\n // 获取"html"之后的子字符串\n subStr := url[index+len("html"):]\n\n // 使用正则表达式匹配第一个"\u0026"之前的内容\n re := regexp.MustCompile(`^(.*?)\u0026`)\n match := re.FindStringSubmatch(subStr)\n if len(match) > 1 {\n fmt.Println(match[1])\n } else {\n fmt.Println("未找到匹配的内容")\n }\n}\n\n\n输出结果为:\n\n\n?clusterid=10000036\n\n\n请注意,由于正则表达式中的反斜杠是特殊字符,所以需要使用两个反斜杠来转义。
原文地址: https://www.cveoy.top/t/topic/pKxK 著作权归作者所有。请勿转载和采集!