使用 go run testregexp.go 运行该文件即可
package main
import (
"fmt"
"regexp"
"net/http"
"io/ioutil"
"strings"
)
/*
通过正则判断是否匹配
regexp包中含有三个函数用来判断是否匹配,如果匹配返回true,否则返回false
func Match(pattern string, b []byte) (matched bool, error error)
func MatchReader(pattern string, r io.RuneReader) (matched bool, error error)
func MatchString(pattern string, s string) (matched bool, error error)
面的三个函数实现了同一个功能,就是判断pattern是否和输入源匹配,匹配的话就返回true,如果解析正则出错则返回error。三个函数的输入源分别是byte slice、RuneReader和string。
*/
func main() {
ip := "127.0.0.1"
res := isip(ip)
if !res{
fmt.Println(ip," 不是ip")
}else{
fmt.Println(ip," 是ip")
}
ip = "127.0.0.1.0"
res = isip(ip)
if !res{
fmt.Println(ip," 不是ip")
}else{
fmt.Println(ip," 是ip")
}
fmt.Println()
vars := "1134"
res = isnumber(vars)
if !res {
fmt.Println(vars," 不是数字")
}else{
fmt.Println(vars," 是数字")
}
vars = "13.2"
res = isnumber(vars)
if !res {
fmt.Println(vars," 不是数字")
}else{
fmt.Println(vars," 是数字")
}
vars = ".234"
res = isnumber(vars)
if !res {
fmt.Println(vars," 不是数字")
}else{
fmt.Println(vars," 是数字")
}
vars = "123abv"
res = isnumber(vars)
if !res {
fmt.Println(vars," 不是数字")
}else{
fmt.Println(vars," 是数字")
}
//正则替换
fmt.Println()
fmt.Println("spiders")
spiders()
//正则查找
fmt.Println()
fmt.Println("regexpfind")
regexpfind()
//expend
fmt.Println()
fmt.Println("testexpend")
testexpend()
}
//验证是不是ip地址
func isip(ip string) bool {
regexp1 := `^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$`
if m,_ := regexp.MatchString(regexp1,ip);!m{
return false
}
return true
}
//验证数字
func isnumber(num string) bool{
regexp1 := `^[0-9]+$`
//判断是否整数
if m,_ := regexp.MatchString(regexp1,num);!m{
//判断是否浮点数
regexp2 := `^[0-9]*\.[0-9]+$`
if m,_ := regexp.MatchString(regexp2,num);!m {
return false
}else{
return true
}
}
return true
}
//正则替换字符串
func spiders(){
resp,err := http.Get("http://www.baidu.com")
if err != nil{
fmt.Println("http get error.")
}
defer resp.Body.Close()
body,err := ioutil.ReadAll(resp.Body)
if err != nil{
fmt.Println("http read error")
return
}
src := string(body)
//fmt.Println();
//fmt.Println("src1",src);
//将html标签全部替换成小写
re,_ := regexp.Compile("\\<[\\S\\s]+?\\>")
src = re.ReplaceAllStringFunc(src,strings.ToLower)
//去除style
re,_ = regexp.Compile(`