go實踐二十三 使用正則

編輯一個 testregexp.go 文件,內容如下

使用 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(`<style([\s\S]*?)</style>`)
	src = re.ReplaceAllString(src,"")

	//去除script
	re,_ = regexp.Compile(`<script([\s\S]*?)</script>`)
	src = re.ReplaceAllString(src,"")

	//去除所有尖括號內的html代碼,並換成換行符
	re,_ = regexp.Compile("\\<[\\S\\s]+?\\>")
	src = re.ReplaceAllString(src,"\n")

	//去除連續的換行符
	re,_ = regexp.Compile("\\s{2,}")
	src = re.ReplaceAllString(src,"\n")

	fmt.Println(strings.TrimSpace(src))
}

func regexpfind(){
	a := "i am learning go language"

	//正則匹配 a-z 字母 2-4 個
	re,_ := regexp.Compile("[a-z]{2,4}")

	//查找符合正則的第一個
	one := re.Find([]byte(a))
	fmt.Println("find:",string(one))

	//查找符合正則的所有slice ,n小於0表示返回全部符合的字符串,不然就是返回指定的長度
	//regexp.Compile(regexp).FindAll([]byte(string),n)
	all := re.FindAll([]byte(a),-1)
	fmt.Println("FindAll",all)

	//查找符合條件的index位置,開始位置和結束位置
	//regexp.Compile(regexp).FindIndex([]byte(string))
	index := re.FindIndex([]byte(a))
	fmt.Println("FindIndex",index)

	//查找符合條件的所有index 的位置, n同上
	//regexp.Compile(regexp).FindAllIndex([]byte(string),n)
	allindex := re.FindAllIndex([]byte(a),-1)
	fmt.Println("FindAllIndex",allindex)

	//正則匹配 am所有lang所有
	re2,_ := regexp.Compile("am(.*)lang(.*)")

	//查找Submatch, 返回數組,第一個元素是匹配的全部元素,第二個元素是第一個()裏面的,第三個是第二個()裏面的
	//下面的輸出第一個元素是"am learning Go language"
	//第二個元素是"learning Go",注意保護空格的輸出
	//第三個元素是"uage"
	submatch := re2.FindSubmatch([]byte(a))
	fmt.Println("FindSubmatch",submatch)
	for _,v := range submatch{
		fmt.Println(string(v))
	}

	//定義和上面的FindIndex一樣
	submatchindex := re2.FindSubmatchIndex([]byte(a))
	fmt.Println(submatchindex)

	//FindAllSubmatch,查找所有符合條件的子匹配
	submatchall := re2.FindAllSubmatch([]byte(a),-1)
	fmt.Println(submatchall)

	//FindAllSubmatchIndex,查找所有字匹配的index
	submatchallindex := re2.FindAllSubmatchIndex([]byte(a),-1)
	fmt.Println(submatchallindex)
}

func testexpend(){
	src := []byte(`
		call hello alice
		hello bob
		call hello eve
	`)
	pat := regexp.MustCompile(`(?m)(call)\s+(?P<cmd>\w+)\s+(?P<arg>.+)\s*$`)
	res := []byte{}
	for _, s := range pat.FindAllSubmatchIndex(src, -1) {
		res = pat.Expand(res, []byte("$cmd('$arg')\n"), src, s)
	}
	fmt.Println(string(res))
}

參考:https://www.golang123.com/book/9?chapterID=180

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章