個人常用函數
1
2
3
4
5
6
7
8
|
func IsContain(items []string, item string) bool { for _, eachItem := range items { if eachItem == item { return true } } return false } |
使用方法
1
2
3
4
5
6
7
|
var word := "my" var sentence := []string{"my","word","in","a","sentence"} if IsContain(sentence){ //包含 }else{ //不包含 } |
補充:golang中的正則匹配&判斷元素是否在slice里或者數組里
1、正則匹配
1
2
3
4
5
6
7
8
9
10
11
12
|
package main import ( "fmt" "regexp" ) func main() { //pattern := "\\d+" //反斜杠要轉義 pattern := "[a-zA-Z]" //匹配字母 str := "a1.22.35.4" result, _ := regexp.MatchString(pattern, str) fmt.Println(result) //true } |
2、判斷元素是否在slice里或者數組里
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package main import "fmt" import "github.com/wxnacy/wgo/arrays" //go get github.com/wxnacy/wgo/arrays 安裝包 func main() { str := "342" var numbers []string numbers = append(numbers, "3332", "342", "ssddd", "ssss", "%%%%") index := arrays.ContainsString(numbers, str) if index == -1 { fmt.Printf("not exists") //-1說明不存在 } else { fmt.Println(index) //存在則會返回元素的下標 } } |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。如有錯誤或未考慮完全的地方,望不吝賜教。
原文鏈接:https://blog.csdn.net/m0_37422289/article/details/103570799