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