How to detect URL with regular expression in Golang?

WBOY
Release: 2024-05-31 10:32:32
Original
652 people have browsed it

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

如何在 Golang 中用正则表达式检测 URL?

如何在 Golang 中用正则表达式检测 URL?

正则表达式是一种强大的工具,用于在文本中查找特定模式。在 Golang 中,我们可以使用正则表达式来验证 URL 是否有效。

语法

Golang 中使用正则表达式的语法如下:

regexp.MustCompile(pattern)
Copy after login

其中,pattern 是要匹配的正则表达式模式。

模式

对于 URL,我们需要一个模式来匹配以下元素:

  • 协议(例如 https:// 或 http://)
  • 主机名
  • 端口(可选)
  • 路径(可选)
  • 查询参数(可选)

我们可以使用下面的正则表达式模式:

^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$
Copy after login

实战案例

下面是一个使用正则表达式检测 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)
        }
    }
}
Copy after login

输出:

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
Copy after login

The above is the detailed content of How to detect URL with regular expression in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!