删除Golang中包含某些子字符串的行

时间:2014-12-11 07:21:33

标签: go string-parsing

如何删除以[]byte中某些子字符串开头的行,Ruby通常我会这样做:

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

如何在Go上执行此操作?

2 个答案:

答案 0 :(得分:7)

你可以用regexp来模仿:

re := regexp.MustCompile("(?m)[\r\n]+^.*substring.*$")
res := re.ReplaceAllString(s, "")

OP Kokizzu went"(?m)^.*" +substr+ ".*$[\r\n]+"

请参阅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)
}

输出:

aaaaa
bbbb
eeee
ffff

请注意使用regexp flag (?m)

  

多行模式:^$匹配开头/结尾行以及开头/结尾文本(默认为false)

答案 1 :(得分:2)

我认为使用bytes包执行此任务比使用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
}

输出:

aaaa
bbbb

Try it here.

相关问题