go +mongoDB模糊匹配通过正则匹配regex时候特殊字符问题
在开发中遇到一个奇怪问题,如果正则匹配中出现了+
开头的去匹配资源名和描述时候,会导致报错,代码如下:
// 模糊匹配资源名&描述
if searchBy := appG.C.DefaultQuery("searchBy", ""); searchBy != "" {
regex := bson.M{"$regex": searchBy}
or := []bson.M{{"name": regex}, {"description": regex}}
BsonM := bson.M{
"$or": or,
}
query = append(query, BsonM)
}
会出现报错情况:Regular expression is incalid: nothing to repeat
所以自己写了一个正则匹配特殊字符转换的小函数:
// 模糊匹配资源名&描述
if searchBy := appG.C.DefaultQuery("searchBy", ""); searchBy != "" {
EscapeString := CheckRegexString1(searchBy)
log.Println(EscapeString)
regex := bson.M{"$regex": EscapeString}
or := []bson.M{{"name": regex}, {"description": EscapeString}}
BsonM := bson.M{
"$or": or,
}
query = append(query, BsonM)
}
func CheckRegexString1(str string) string {
//正则匹配出现的特殊字符串
fbsArr := []string{"\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|"}
for _, ch := range fbsArr {
if StrContainers := strings.Contains(str, ch); StrContainers == true {
str = strings.Replace(str, ch, "\\"+ch, -1)
}
}
return str
}
功能目前上线后跑起来是正常的,需要后续观察一下时候存在一些特殊的字符没有包括进来。