Go 中是否有任何方法或正则表达式可以只删除字符串中使用的冠词?
我试过下面的代码可以做到这一点,但它也会从我正在显示下面代码的字符串中删除其他单词:
removalString := "This is a string"
stringToRemove := []string{"a", "an", "the", "is"}
for _, wordToRemove := range stringToRemove {
removalString = strings.Replace(removalString, wordToRemove, "", -1)
}
space := regexp.MustCompile(`\s+`)
trimedExtraSpaces := space.ReplaceAllString(removalString, " ")
spacesCovertedtoDashes := strings.Replace(trimedExtraSpaces, " ", "-", -1)
slug := strings.ToLower(spacesCovertedtoDashes)
fmt.Println(slug)
已编辑
在此它将删除 this
中使用的 is
。
预期输出是this-string
最佳答案
您可以使用 strings.Split
和 strings.Join
加上一个用于过滤的循环,然后再次将其构建在一起:
removalString := "This is a string"
stringToRemove := []string{"a", "an", "the", "is"}
filteredStrings := make([]string, 0)
for _, w := range strings.Split(removalString, " ") {
shouldAppend := true
lowered := strings.ToLower(w)
for _, w2 := range stringToRemove {
if lowered == w2 {
shouldAppend = false
break
}
}
if shouldAppend {
filteredStrings = append(filteredStrings, lowered)
}
}
resultString := strings.Join(filteredStrings, "-")
fmt.Printf(resultString)
输出:
this-string
Program exited.
这里有 live example
关于regex - 使用 Go 从字符串中删除所有文章和其他字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53479885/