Delete lines containing a specific substring in Golang
2 answers
You can emulate this with a regular expression:
re := regexp.MustCompile("(?m)[\r\n]+^.*substring.*$")
res := re.ReplaceAllString(s, "")
( OP Kokizzu went with "(?m)^.*" +substr+ ".*$[\r\n]+"
)
See this example
func main() {
s := `aaaaa
bbbb
cc substring ddd
eeee
ffff`
re := regexp.MustCompile("(?m)[\r\n]+^.*substring.*$")
res := re.ReplaceAllString(s, "")
fmt.Println(res)
}
output:
aaaaa
bbbb
eeee
ffff
Notice the use of regexp flag (? M) :
multiline mode:
^
and$
matches the start / end of the line in addition to the start / end of the text (default false)
+5
source to share
I find using a package bytes
for this task is better than using regexp
.
package main
import (
"fmt"
"bytes"
)
func main() {
myString := []byte("aaaa\nsubstring\nbbbb")
lines := bytes.Replace(myString, []byte("substring\n"), []byte(""), 1)
fmt.Println(string(lines)) // Convert the bytes to string for printing
}
Output:
aaaa
bbbb
+1
source to share