如何在 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 中,我们可以使用 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])$
登录后复制
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")
}
}
登录后复制
实战案例
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)
}
登录后复制
输出:
The IP address of the web server is <REDACTED>. The database server has the IP address <REDACTED>.
登录后复制
以上就是如何在 Go 中用正则表达式匹配 IP 地址?的详细内容,更多请关注叮当号网其它相关文章!
文章来自互联网,只做分享使用。发布者:周斌,转转请注明出处:https://www.dingdanghao.com/article/478143.html
