Update zh/07.3.md
more reable code
This commit is contained in:
11
zh/07.3.md
11
zh/07.3.md
@@ -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("不是数字")
|
||||
|
||||
Reference in New Issue
Block a user