github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/06_xmljson/reg/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  )
     7  
     8  func main() {
     9  	a := "I am learning Go language"
    10  	re, _ := regexp.Compile("[a-z]{2,4}")
    11  	//查找符合正则的第一个
    12  	one := re.Find([]byte(a))
    13  	fmt.Println("Find:", string(one))
    14  	//查找符合正则的所有slice,n小于0表示返回全部符合的字符串,不然就是返回指定的长度
    15  	all := re.FindAll([]byte(a), -1)
    16  	fmt.Println("FindAll", all)
    17  	//查找符合条件的index位置,开始位置和结束位置
    18  	index := re.FindIndex([]byte(a))
    19  	fmt.Println("FindIndex", index)
    20  	//查找符合条件的所有的index位置,n同上
    21  	allindex := re.FindAllIndex([]byte(a), -1)
    22  	fmt.Println("FindAllIndex", allindex)
    23  	re2, _ := regexp.Compile("am(.*)lang(.*)")
    24  
    25  	//查找Submatch,返回数组,第一个元素是匹配的全部元素,第二个元素是第一个()里面的,第三个是第二个()里面的
    26  	//下面的输出第一个元素是"am learning Go language"
    27  	//第二个元素是" learning Go ",注意包含空格的输出
    28  	//第三个元素是"uage"
    29  	submatch := re2.FindSubmatch([]byte(a))
    30  	fmt.Println("FindSubmatch", submatch)
    31  	for _, v := range submatch {
    32  		fmt.Println(string(v))
    33  	}
    34  	//定义和上面的FindIndex一样
    35  	submatchindex := re2.FindSubmatchIndex([]byte(a))
    36  	fmt.Println(submatchindex)
    37  	//FindAllSubmatch,查找所有符合条件的子匹配
    38  	submatchall := re2.FindAllSubmatch([]byte(a), -1)
    39  	fmt.Println(submatchall)
    40  	//FindAllSubmatchIndex,查找所有字匹配的index
    41  	submatchallindex := re2.FindAllSubmatchIndex([]byte(a), -1)
    42  	fmt.Println(submatchallindex)
    43  }