regex - 使用 Go 从字符串中删除所有文章和其他字符串?

标签 regex string go

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)

已编辑

Play link

在此它将删除 this 中使用的 is

预期输出是this-string

最佳答案

您可以使用 strings.Splitstrings.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/

相关文章:

Ruby .gsub 如何缩短进行类似替换的代码行

unit-testing - 如何在 Go 中获得所有包的代码覆盖率?

正则表达式只匹配第一行?

javascript - 如何过滤掉以空格分隔的单词?

javascript - 拆分前两个空格的字符串

mongodb - 在 Golang 和 MongoDB 中使用 $lookup 和 $unwind 请求缓慢

go - 我如何在 Go 中以相同的方式对来自多个 channel 的输入使用react?

java - 在 ","上 split ,但不在 "\,"上 split

正则表达式替换 "and "之间的 href 值,用于 <a> 而不是 <link> 标签

c++ - 如何将字符串中的多个数字转换为整数