Golang删除两个特定字符串之间的所有文本



go/golang是否可以删除两个字符串之间的所有内容?我有一个input.txt文件,它的结构如下:

#start-kiwi
this text
is important
#end-kiwi
#start-banana
this text
needs to be
completely removed
#end-banana
#start-orange
this text
is also important
#end-orange

从go代码中,我试图删除标记#start-banana#end-banana之间的所有内容(包括两者(,因此所需结果为:

#start-kiwi
this text
is important
#end-kiwi
#start-orange
this text
is also important
#end-orange

我正在使用go 1.19,我已经尝试过这些方法:

string.Contains(strings.Replace(input.txt, "#start-banana", "")
string.Contains(strings.Replace(input.txt, "#end-banana", "")

但它似乎不太好用。有什么更好的方法可以实现这一点吗?RegEx?使用strings库?

提前谢谢。

您可以使用索引来界定必须删除的文本部分:

package main
import (
"fmt"
"strings"
)
func main() {
data := `
#start-kiwi
this text
is important
#end-kiwi
#start-banana
this text
needs to be
completely removed
#end-banana
#start-orange
this text
is also important
#end-orange`
start := "#start-banana"
stop := "#end-banana"
startIndex := strings.Index(data, start)
stopIndex := strings.Index(data, stop) + len(stop)
res := data[:startIndex] + data[stopIndex:]
res = strings.ReplaceAll(res, "nn", "n")
fmt.Println(res)
}

结果如下:

#start-kiwi
this text
is important
#end-kiwi
#start-orange
this text
is also important
#end-orange

您还可以使用正则表达式:

package main
import (
"fmt"
"regexp"
)
func main() {
s := removeBetween(text, "#start-banana", "#end-banana[nr]?")
fmt.Println(s)
}
// removeBetween removes all characters (including new lines) between the start and end markers
func removeBetween(str, start, end string) string {
anyIncludingEndLine := fmt.Sprintf(`%s[rnsw]*%s`, start, end)
return regexp.MustCompile(anyIncludingEndLine).ReplaceAllString(str, "")
}
var text = `
#start-kiwi
this text
is important
#end-kiwi
#start-banana
this text
needs to be
completely removed
#end-banana
#start-orange
this text
is also important
#end-orange
`

最新更新