Home > Backend Development > Golang > How to match IP address with regular expression in Go?

How to match IP address with regular expression in Go?

WBOY
Release: 2024-05-31 21:35:38
Original
1038 people have browsed it

如何在 Go 中使用正则表达式匹配 IP 地址?正则表达式语法:^(([0-9]|1-9|1[0-9]{2}|20-4|25[0-5]).){3}([0-9]|1-9|1[0-9]{2}|20-4|25[0-5])$Go 代码示例:使用 regexp.MatchString() 函数进行匹配。实战案例:使用 regexp.MustCompile() 函数从字符串中替换所有 IP 地址。

如何在 Go 中用正则表达式匹配 IP 地址?

如何在 Go 中用正则表达式匹配 IP 地址?

正则表达式是一种强大的工具,可用于在字符串中搜索和匹配模式。在 Go 中,我们可以使用 regexp 包轻松地使用正则表达式。

正则表达式语法

匹配 IP 地址的正则表达式语法如下:

^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$
Copy after login

Go 代码示例

以下代码演示了如何使用 regexp 包匹配 IP 地址:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    ipAddress := "192.168.1.1"
    
    matched, _ := regexp.MatchString(`^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$`, ipAddress)
    
    if matched {
        fmt.Println("IP address is valid")
    } else {
        fmt.Println("IP address is invalid")
    }
}
Copy after login

实战案例

regexp 包还提供了其他有用的功能,例如替换和分组。以下代码演示了如何使用 regexp 包从字符串中替换所有 IP 地址:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    text := "The IP address of the web server is 192.168.1.1. The database server has the IP address 10.0.0.1."
    
    // 匹配所有 IP 地址
    ips := regexp.MustCompile(`(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])(\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])){3}`)
    
    // 替换所有 IP 地址
    result := ips.ReplaceAllString(text, "<REDACTED>")
    
    fmt.Println(result)
}
Copy after login

输出:

The IP address of the web server is <REDACTED>. The database server has the IP address <REDACTED>.
Copy after login

The above is the detailed content of How to match IP address with regular expression in Go?. 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