How to remove lines that started with certain substring in []byte
, in Ruby
usually I do something like this:
lines = lines.split("\n").reject{|r| r.include? 'substring'}.join("\n")
How to do this on Go
?
You could emulate that with regexp:
re := regexp.MustCompile("(?m)[\r\n]+^.*substring.*$")
res := re.ReplaceAllString(s, "")
(The 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
Note the use of regexp flag (?m):
multi-line mode:
^
and$
match begin/end line in addition to begin/end text (default false)
I believe using the bytes
package 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.
I believe using the bytes
package 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With