I have a simple question about keywords searching in a Go.
I want to search a string using positive and negative keywords
func keyword(itemTitle string, keywords string) bool {
splits := strings.Split(keywords, ",")
for _, item := range splits {
item = strings.TrimSpace(item)
fmt.Println(strings.ToUpper(itemTitle))
fmt.Println(strings.ToUpper(item))
if strings.Contains(item,"-") {
item = item[1:]
if strings.Contains(strings.ToUpper(itemTitle), strings.ToUpper(item)) {
return false
}
}
item = item[1:]
fmt.Println(strings.ToUpper(item))
if strings.Contains(strings.ToUpper(itemTitle), strings.ToUpper(item)) {
return true
}
}
return false
}
heres my searcher method
func TestKeyword(t *testing.T) {
test1 := "Pokemon Nintendo Switch Cool Thing"
keywordTest1 := " pokemon,-nintendo"
if keyword(test1, keywordTest1) {
fmt.Println("matched")
} else {
fmt.Println("test")
}
test2 := "Pokemon Cards Cool"
if keyword(test2, keywordTest1) {
fmt.Println("matched")
} else {
fmt.Println("test")
}
}
my test cases i understand why its not working because amd is the first in the slice and its ofc going to return true and not test any of the other like -radeon but im just kinda stumped on what todo.
Output given
matched
matched
Expected Output
test
matched
CodePudding user response:
I updated your search function but kept the signature
func keyword(itemTitle string, keywords string) bool {
a := strings.ToUpper(itemTitle)
b := strings.ToUpper(keywords)
keys := strings.Split(strings.Replace(b, "-", " ", -1), ",")
for _, key := range keys {
key = strings.TrimSpace(key)
if strings.Contains(a, key) {
return true
}
}
return false
}
And updated your test function with a passing test and a failed one to see how it works.
func TestKeyword(t *testing.T) {
test1 := "Pokemon Nintendo Switch Cool Thing"
keywordTest1 := " pokemon,-nintendo"
if keyword(test1, keywordTest1) {
t.Log("matched")
} else {
t.Fail()
}
test2 := "Pokemon Cards Cool"
if keyword(test2, keywordTest1) {
t.Log("matched")
} else {
t.Fail()
}
}
Regarding the second test failing with a keyword with on it, you could pass that through a regex to get only alphanumeric characters, if required.