The use of the regular expression of the go language is simple, the sample code:
Package Testimport ("FMT" "RegExp") func regixbase () {//findtest ()//findindextest ()//findstringtest ()// Findchinesstring ()//findnumorlowerletter () Findandreplace ()}//incoming []byte, return []bytefunc findtest () {str: = " Ab001234hah120210a880218end "REG: = RegExp. Mustcompile ("\\d{6}")//six-bit continuous digital FMT. PRINTLN ("------Find------")//returns the first string matching reg in str data: = Reg. Find ([]byte (str)) FMT. Println (String (data)) FMT. PRINTLN ("------FindAll------")//Returns all matching Reg strings in str//The second parameter represents the maximum number returned, and 1 means that all results are returned dataslice: = Reg. FindAll ([]byte (str),-1) for _, V: = Range Dataslice {fmt. Println (String (v))}}//incoming []byte, returns the first position index func findindextest () {fmt. PRINTLN ("------findindex------")//returns the first end of a matching string REG2: = RegExp. Mustcompile ("Start\\d*end")//start start, end ends, middle is all digital str2: = "00start123endhahastart120psend09start10000end"//index[ 0] Indicates the start position, index[1] indicates the end position index: = reg2. FindIndex ([]byte (STR2)) fmt. Println ("Start:", Index[0], ", End:", index[1], str2[index[0]:index[1]]) fmt. PRINTLN ("------findallindex------")//Returns all matching string first position indexslice: = reg2. FindallindeX ([]byte (STR2),-1) for _, V: = Range Indexslice {fmt. Println ("Start:", V[0], ", End:", v[1], str2[v[0]:v[1]])}}//incoming string, returns a string (more convenient) func findstringtest () {fmt. PRINTLN ("------FindString------") str: = "Ab001234hah120210a880218end" reg: = RegExp. Mustcompile ("\\d{6}")//six-bit continuous digital FMT. Println (Reg. FindString (str)) FMT. Println (Reg. Findallstring (str,-1))//The following two methods are similar to FMT. Println (Reg. Findstringindex (str)) FMT. Println (Reg. FindIndex ([]byte (str)))}//find Chinese character func findchinesstring () {str: = "Hello china Hello World Peace Hi Good" reg: = RegExp. Mustcompile ("[\\p{han}]+") fmt. Println (Reg. Findallstring (str,-1))//[China World Peace Good]}//find a number or lowercase letter func findnumorlowerletter () {str: = "Haha00azbapabc09fgabhy99" REG: = Regexp. Mustcompile ("[\\d|a-z]+") fmt. Println (Reg. Findallstring (str,-1))//[00az abc09 ab 99]}//find and replace Func findandreplace () {str: = "Welcome for Beijing-tianjin CRH train." Reg: = RegExp. Mustcompile ("") fmt. Println (Reg. Replaceallstring (str, "@"))//Replace the space with the @ character//[email protected]@[email protected] @train.}
Go language: Use of regular expressions