Delete lines containing a specific substring in Golang

How can I delete lines that started with a specific substring in []byte

, Ruby

usually I do something like this:

lines = lines.split("\n").reject{|r| r.include? 'substring'}.join("\n")

      

How to do it on Go

?

+3


source to share


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


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

      

Try it here.

+1


source







All Articles