个人常用函数
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