go多分隔符切割字符串

问题描述

在解析k8s污点的时候,结构有两种:

k1=v1:NoSchedule

k2:NoSchedule

即,代码中我需要分别获取其key、value、effect的数值来赋值。(value可以为空。effect为TaintEffect类型非string)

问题解决

使用strings包的FieldsFunc方法,参数1为待分割字符串;参数2为自定义函数

func main() {
	str := "a:bb=c+d%6"
	dist0 := strings.FieldsFunc(str, SplitByMoreStr)
	fmt.Println(dist0)

	str1 := "k2:NoSchedule"
	dist1 := strings.FieldsFunc(str1,SplitByMoreStr)
	fmt.Println(dist1)

	str2 := "k1=v1:NoSchedule"
	dist1 := strings.FieldsFunc(str2,SplitByMoreStr)
	fmt.Println(dist1)
}

func SplitByMoreStr(r rune) bool {
    //常用分隔符可以都写上
	return r == ':' || r == '=' || r == '+' || r == '-' || r == '*' || r == '/'
}

打印:
[a bb c d 6]
[k2 NoSchedule]
[k1 v1 NoSchedule]

显然达到了目的。是不是美滋滋!

其中SplitByMoreStr定义了你分割字符串时需要按哪些字符来分割。FieldsFunc方法返回值是一个string类型的切片,只需要按下标获取对应的值即可。

源码分析

// FieldsFunc splits the string s at each run of Unicode code points c satisfying f(c)
// and returns an array of slices of s. If all code points in s satisfy f(c) or the
// string is empty, an empty slice is returned.
// FieldsFunc makes no guarantees about the order in which it calls f(c).
// If f does not return consistent results for a given c, FieldsFunc may crash.
func FieldsFunc(s string, f func(rune) bool) []string {
	// A span is used to record a slice of s of the form s[start:end].
	// The start index is inclusive and the end index is exclusive.
	type span struct {
		start int
		end   int
	}
	spans := make([]span, 0, 32)

	// Find the field start and end indices.
	wasField := false
	fromIndex := 0
	for i, rune := range s {
		if f(rune) {
			if wasField {
				spans = append(spans, span{start: fromIndex, end: i})
				wasField = false
			}
		} else {
			if !wasField {
				fromIndex = i
				wasField = true
			}
		}
	}

	// Last field might end at EOF.
	if wasField {
		spans = append(spans, span{fromIndex, len(s)})
	}

	// Create strings from recorded field indices.
	a := make([]string, len(spans))
	for i, span := range spans {
		a[i] = s[span.start:span.end]
	}

	return a
}

以上面待传字符串a:bb=c+d%6为例,其中遍历s的过程如下:

0    97
1    58
2    98
3    98
4    61
5    99
6    43
7    100
8    37
9    54

FieldsFunc方法会判断SplitByMoreStr定义的字符,字符串中有这些字符的会走if f(rune) {...},将带分隔的字符存入切片,最后返回这个切片。

使用时根据待分割字符串的特征相应修改函数f中定义的分隔符即可。

你可能感兴趣的:(#,go)