golang 正则表达式 匹配域名 IP
在Go语言中,可以使用regexp
标准库来匹配域名和IP地址。以下是一个示例代码,演示如何使用正则表达式来匹配这两者:
package main
import (
"fmt"
"regexp"
)
func main() {
// 正则表达式用于匹配IP地址
ipRegex := regexp.MustCompile(`^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$`)
// 正则表达式用于匹配域名
domainRegex := regexp.MustCompile(`^([a-zA-Z0-9][a-zA-Z0-9\-]{1,61}[a-zA-Z0-9]\.)+[a-zA-Z0-9]{2,6}$`)
// 测试字符串
testStr1 := "192.168.1.1"
testStr2 := "example.com"
// 检查是否为IP地址
if ipRegex.MatchString(testStr1) {
fmt.Printf("%s is an IP address\n", testStr1)
} else {
fmt.Printf("%s is not an IP address\n", testStr1)
}
// 检查是否为域名
if domainRegex.MatchString(testStr2) {
fmt.Printf("%s is a domain name\n", testStr2)
} else {
fmt.Printf("%s is not a domain name\n", testStr2)
}
}