golang正则regexp包使用-05-扩展Expand()、根据正则切割Split()

1. 扩展

1.1 Expand()方法

语法

func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte

说明

  • template的结果添加到dst后边
  • template中有 $1 $2 ……,这些变量可以在 src中找到。
  • match是对src对应组的解析。

完整示例

package main

import (
	"fmt"
	"regexp"
)

func main() {
    
    
	reg := regexp.MustCompile(`(.*),(.*),(.*)`)
	src := []byte("刘,备,玄德")
	dst := []byte("人员信息:")
	template := []byte("姓$1 名$2 字$3")
	match := reg.FindSubmatchIndex(src)
	s := reg.Expand(dst, template, src, match)
	fmt.Printf("%s\n",s)
}
  • 结果
人员信息:姓刘 名备 字玄德

1.2 ExpandString() 方法

语法

func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte

完整示例

  • 代码
package main

import (
	"fmt"
	"regexp"
)

func main() {
    
    
	reg := regexp.MustCompile(`(.*),(.*),(.*)`)
	src := "刘,备,玄德"
	dst := []byte("人员信息:")
	template := "姓$1 名$2 字$3"
	match := reg.FindStringSubmatchIndex(src)
	s := reg.ExpandString(dst, template, src, match)
	fmt.Printf("%s\n",s)
}
  • 示例
人员信息:姓刘 名备 字玄德

2. 根据正则切割

2.1 Split() 方法

语法

func (re *Regexp) Split(s string, n int) []string

说明:

  • n > 0:最多分割几个子字串(切够了最后一个就不切了)
  • n == 0:返回空
  • n < 0:有多少切多少,返回所有结果

完整示例

  • 代码
package main

import (
	"fmt"
	"regexp"
)

func main() {
    
    
	myString := "10.10.239.11"
	reg := regexp.MustCompile(`\.`)
	resultList := reg.Split(myString,-1)
	fmt.Printf("%q",resultList)
}
  • 结果
["10" "10" "239" "11"]

示例(n不同值的结果)

package main

import (
	"fmt"
	"regexp"
)

func main() {
    
    
	myString := "10.10.239.11"
	reg := regexp.MustCompile(`\.`)
	fmt.Printf("n=-1:%q\n",reg.Split(myString,-1))
	fmt.Printf("n=0:%q\n",reg.Split(myString,0))
	fmt.Printf("n=1:%q\n",reg.Split(myString,1))
	fmt.Printf("n=2:%q\n",reg.Split(myString,2))
	fmt.Printf("n=3:%q\n",reg.Split(myString,3))
}
  • 结果
n=-1["10" "10" "239" "11"]
n=0[]
n=1["10.10.239.11"]
n=2["10" "10.239.11"]
n=3["10" "10" "239.11"]

n=-1,完全切割,且返回了所有切割结果。
n=0,返回空。
n=1,切割成一个子字串,相当于没有切割
n=2,切割成两个子字串,第一个正常切,第二个是最后一个了,不切了,返回剩余所有。
n=3,切割成三个子字串,前两个正常切,第三个是最后一个了,不切了,返回剩余所有。

猜你喜欢

转载自blog.csdn.net/xingzuo_1840/article/details/125377427
今日推荐