github.com/siglens/siglens@v0.0.0-20240328180423-f7ce9ae441ed/pkg/utils/stringutils.go (about) 1 /* 2 Copyright 2023. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package utils 18 19 import ( 20 "regexp" 21 "strings" 22 23 "github.com/siglens/siglens/pkg/common/dtypeutils" 24 log "github.com/sirupsen/logrus" 25 ) 26 27 // Converts a string like `This has "quotes"` to `This has \"quotes\"` 28 func EscapeQuotes(s string) string { 29 result := "" 30 for _, ch := range s { 31 if ch == '"' { 32 result += "\\" 33 } 34 35 result += string(ch) 36 } 37 38 return result 39 } 40 41 // Return all strings in `slice` that match `s`, which may have wildcards. 42 func SelectMatchingStringsWithWildcard(s string, slice []string) []string { 43 if strings.Contains(s, "*") { 44 s = dtypeutils.ReplaceWildcardStarWithRegex(s) 45 } 46 47 // We only want exact matches. 48 s = "^" + s + "$" 49 50 compiledRegex, err := regexp.Compile(s) 51 if err != nil { 52 log.Errorf("SelectMatchingStringsWithWildcard: regex compile failed: %v", err) 53 return nil 54 } 55 56 matches := make([]string, 0) 57 for _, potentialMatch := range slice { 58 if compiledRegex.MatchString(potentialMatch) { 59 matches = append(matches, potentialMatch) 60 } 61 } 62 63 return matches 64 }