使用正则表达式在 golang 中检测 url 的步骤如下:使用 regexp.mustcompile(pattern) 编译正则表达式模式。模式需匹配协议、主机名、端口(可选)、路径(可选)和查询参数(可选)。使用 regexp.matchstring(pattern, url) 检测 url 是否匹配模式。

正则表达式是一种强大的工具,用于在文本中查找特定模式。在 Golang 中,我们可以使用正则表达式来验证 URL 是否有效。
Golang 中使用正则表达式的语法如下:
regexp.MustCompile(pattern)
其中,pattern 是要匹配的正则表达式模式。
立即学习“go语言免费学习笔记(深入)”;
对于 URL,我们需要一个模式来匹配以下元素:
我们可以使用下面的正则表达式模式:
^(https?://)?([da-z.-]+).([a-z.]{2,6})([/w .-]*)*/?$下面是一个使用正则表达式检测 URL 的实战案例:
package main
import (
"fmt"
"regexp"
)
func main() {
// 要检测的 URL
urls := []string{
"https://www.google.com",
"http://example.com",
"ftp://ftp.example.com",
"example.com",
"127.0.0.1",
"google.com",
}
// 正则表达式模式
pattern := "^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$"
for _, url := range urls {
result, err := regexp.MatchString(pattern, url)
if err != nil {
fmt.Println("Error:", err)
}
if result {
fmt.Println("Valid URL:", url)
} else {
fmt.Println("Invalid URL:", url)
}
}
}输出:
Valid URL: https://www.google.com Valid URL: http://example.com Invalid URL: ftp://ftp.example.com Invalid URL: example.com Invalid URL: 127.0.0.1 Invalid URL: google.com
以上就是如何在 Golang 中用正则表达式检测 URL?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号