Update zh/07.3.md

more reable code
This commit is contained in:
胡子豪
2021-03-03 23:23:52 +08:00
committed by GitHub
parent 72d959bfa7
commit c6e9222555

View File

@@ -21,11 +21,9 @@ func MatchString(pattern string, s string) (matched bool, error error)
如果要验证一个输入是不是IP地址那么如何来判断呢请看如下实现
```Go
func IsIP(ip string) (b bool) {
if m, _ := regexp.MatchString("^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$", ip); !m {
return false
}
return true
func IsIP(ip string) (m bool) {
m, _ = regexp.MatchString("^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$", ip)
return
}
```
可以看到,`regexp`的pattern和我们平常使用的正则一模一样。再来看一个例子当用户输入一个字符串我们想知道是不是一次合法的输入
@@ -35,7 +33,8 @@ func main() {
if len(os.Args) == 1 {
fmt.Println("Usage: regexp [string]")
os.Exit(1)
} else if m, _ := regexp.MatchString("^[0-9]+$", os.Args[1]); m {
}
if m, _ := regexp.MatchString("^[0-9]+$", os.Args[1]); m {
fmt.Println("数字")
} else {
fmt.Println("不是数字")