go - 解析文件,忽略注释和空行

标签 go

正如标题所说,我正在尝试解析文件但忽略注释(以 # 开头)或空行。我试图为此建立一个系统,但它似乎总是忽略了它应该忽略注释和/或空行。

lines := strings.Split(d, "\n")
var output map[string]bool = make(map[string]bool)

for _, line := range lines {
    if strings.HasPrefix(line, "#") != true {
        output[line] = true
    } else if len(line) > 0 {
        output[line] = true
    }
}

运行时(这是函数的一部分),输出如下

This is the input ('d' variable):
Minecraft
Zerg Rush
Pokemon

# Hello

This is the output when printed ('output' variable):

map[Minecraft:true Zerg Rush:true Pokemon:true :true # Hello:true]

我的问题是它仍然保留“”和“# Hello”值,这意味着某些事情失败了,我一直无法弄清楚。

那么,我做错了什么会保留不正确的值?

最佳答案

len(line) > 0 对于 "# Hello" 行来说是真的,所以它会被添加到 output

目前,您要添加的行不是以 # 开头或 不为空。您只需要添加满足这两个条件的行:

if !strings.HasPrefix(line, "#") && len(line) > 0 {
    output[line] = true
}

关于go - 解析文件,忽略注释和空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36682205/

相关文章:

go - golang 中的集合

mongodb - 如何使用 mongo-go-driver 模拟光标

http - 为什么我不能将正文添加到 http 重定向?

Go 包不在 $GOROOT 中

go - 如何在 go 模型中包装 proto 消息

go - 比较命名管道和未命名类型时编译错误

go - 从容器内运行的应用程序使用 Gmail API

go - 沙发底座中的 “where not equal to”

go - 为什么 LiteIDE 不构建选中/高亮的 go 文件?

go - redigo 是否重新连接到服务器?