Go 언어:정규 표현 식 사용

Go 언어의 정규 표현 식 사용 은 간단 합 니 다.예제 코드:
package test

import (
	"fmt"
	"regexp"
)

func RegixBase() {
	//findTest()
	//findIndexTest()
	//findStringTest()
	//findChinesString()
	//findNumOrLowerLetter()
	findAndReplace()
}

//  []byte,  []byte
func findTest() {
	str := "ab001234hah120210a880218end"
	reg := regexp.MustCompile("\\d{6}") //       
	fmt.Println("------Find------")
	//  str      reg    
	data := reg.Find([]byte(str))
	fmt.Println(string(data))

	fmt.Println("------FindAll------")
	//  str     reg    
	//              , -1        
	dataSlice := reg.FindAll([]byte(str), -1)
	for _, v := range dataSlice {
		fmt.Println(string(v))
	}
}

//  []byte,        
func findIndexTest() {
	fmt.Println("------FindIndex------")
	//                
	reg2 := regexp.MustCompile("start\\d*end") //start  ,end  ,      
	str2 := "00start123endhahastart120PSend09start10000end"
	//index[0]      ,index[1]      
	index := reg2.FindIndex([]byte(str2))
	fmt.Println("start:", index[0], ",end:", index[1], str2[index[0]:index[1]])

	fmt.Println("------FindAllIndex------")
	//              
	indexSlice := reg2.FindAllIndex([]byte(str2), -1)
	for _, v := range indexSlice {
		fmt.Println("start:", v[0], ",end:", v[1], str2[v[0]:v[1]])
	}
}

//  string,  string(    )
func findStringTest() {
	fmt.Println("------FindString------")

	str := "ab001234hah120210a880218end"
	reg := regexp.MustCompile("\\d{6}") //       
	fmt.Println(reg.FindString(str))
	fmt.Println(reg.FindAllString(str, -1))
	//          
	fmt.Println(reg.FindStringIndex(str))
	fmt.Println(reg.FindIndex([]byte(str)))
}

//    
func findChinesString() {
	str := "hello  hello    hi "
	reg := regexp.MustCompile("[\\p{Han}]+")
	fmt.Println(reg.FindAllString(str, -1))

	//[         ]
}

//         
func findNumOrLowerLetter() {
	str := "HAHA00azBAPabc09FGabHY99"
	reg := regexp.MustCompile("[\\d|a-z]+")
	fmt.Println(reg.FindAllString(str, -1))

	//[00az abc09 ab 99]
}

//     
func findAndReplace() {
	str := "Welcome for Beijing-Tianjin CRH train."
	reg := regexp.MustCompile(" ")
	fmt.Println(reg.ReplaceAllString(str, "@")) //      @  

	//Welcome@for@Beijing-Tianjin@CRH@train.
}

좋은 웹페이지 즐겨찾기