有些场景需要获取字符串按某个字符切割之后,获取最后,有个比较好的实践分享
strings.LastIndex 如果没有匹配到,则返回-1
package mainimport ("fmt""strings"
)func main() {ss := []string{"", ":", "a:", "a:b", "a:b:c", "abc"}/*'' => ''':' => '''a:' => '''a:b' => 'b''a:b:c' => 'c''abc' => 'abc'*/for _, s := range ss {fmt.Printf("'%s' => '%s'\n", s, s[strings.LastIndex(s, ":")+1:])}
}
参考链接:
- go - 返回 Golang 中 strings.Split() slice 的最后一项
- Return last item of strings.Split() slice in Golang