如何在列表中丢弃带有某些字符串的行并输出到新列表

我有一个从XML网站下载的列表。我试图通过丢弃包含特定字符串的行并构建不包含字符串的行的相同类型的列表来筛选列表。 我有一个struct类型,另外一个struct类型。 我正在尝试使用regexpreplaceall,但在replaceall上失败。

func (*Regexp) ReplaceAll
func (re *Regexp) ReplaceAll(src,repl []byte) []byte

可能有一种完全简单的方法将列表过滤到我在某处缺少的新列表中,但是到目前为止,我发现这是最接近的解决方案。请分享其他grep和删除行到新列表的方式。该列表是正文的一个字节,并以xml格式下载。

type PeopleList struct {
    Peoples []Person `xml:"peoples>person"`
}

type Person struct {
    ADD      string `xml:"add,attr"`
    Loc      string `xml:"loc,attr"`
    Har      string `xml:"har,attr"`
    Name     string `xml:"name,attr"`
    Country  string `xml:"country,attr"`
    Num       string `xml:"num,attr"`
    ADD2     string `xml:"add2,attr"`
    Distance float64

func fetchPeopleList(userinfo Userinfo) PeopleList {
    var p byte
    jam,err := http.Get(string(peoplelisturl))
    iferror (err)
    body,err := ioutil.ReadAll(jam.Body)
    peeps := body
    reg := regexp.MustCompile("(?m)[\r\n]+^.*BAD:.*$")
    rep := reg.ReplaceAll(peeps,p) // Here fails probably because of my syntax. Error: cannot use p (variable of type byte) as []byte value in argument to re.ReplaceAll

    fmt.Println(rep)
    iferror (err)
    defer jam.Body.Close()

最后,我想要一个与第一个格式相同的新列表,只是没有包含字符串的行。

keep2100 回答:如何在列表中丢弃带有某些字符串的行并输出到新列表

您的问题是说您要“丢弃行”,但是Replace / ReplaceAll顾名思义,是用来替换匹配的模式。您的正则表达式也是一个简单的子字符串匹配项,因此显而易见的解决方案似乎是逐行读取文件,并且-如您的标题所说-丢弃包含子字符串的行。

func fetchPeopleList(userinfo Userinfo) PeopleList {
    jam,err := http.Get(string(peoplelisturl))
    iferror (err)
    br := bufio.NewReader(jam.Body)
    defer jam.Body.Close()
    for {
        line,err := br.ReadString('\n')
        if !strings.Contains(line,"BAD:") {
            fmt.Println(line) // or whatever you want to do with non-discarded lines
        }
        if err != nil {
            break
        }
    }
本文链接:https://www.f2er.com/3137165.html

大家都在问