我正在尝试将一个简单的降价文件转换为 json,降价看起来像这样:#TITLE 1- Line 1- Line 2- Line 3#TITLE 2- Line 1- Line 2- Line 3<!-- blank line -->我不明白在func main() 中重构以下内容需要什么: type Section struct { Category string Lines []string } file, _ := os.Open("./src/basicmarkdown/basicmarkdown.md") defer file.Close() rgxRoot, _ := regexp.Compile("^#[^#]") rgxBehaviour, _ := regexp.Compile("^-[ ]?.*") scanner := bufio.NewScanner(file) ruleArr := []*Section{} rule := &Section{} for scanner.Scan() { linetext := scanner.Text() // If it's a blank line if rgxRoot.MatchString(linetext) { rule := &Section{} rule.Category = linetext } if rgxBehaviour.MatchString(linetext) { rule.Lines = append(rule.Lines, linetext) } if len(strings.TrimSpace(linetext)) == 0 { ruleArr = append(ruleArr, rule) } } jsonSection, _ := json.MarshalIndent(ruleArr, "", "\t") fmt.Println(string(jsonSection))上面的代码输出:[{ "Category": "", "Lines": [ "- Line 1", "- Line 2", "- Line 3", "- Line 1", "- Line 2", "- Line 3" ] }, { "Category": "", "Lines": [ "- Line 1", "- Line 2", "- Line 3", "- Line 1", "- Line 2", "- Line 3" ] }]当我希望输出时:[ { "Category": "#TITLE 1", "Lines": [ "- Line 1", "- Line 2", "- Line 3" ] }, { "Category": "#TITLE 2", "Lines": [, "- Line 1", "- Line 2", "- Line 3" ] }]肯定有几件事是错的。请原谅这个问题的冗长,当你是一个菜鸟时,如果没有例子就很难解释。提前致谢。
1 回答

呼啦一阵风
TA贡献1802条经验 获得超6个赞
在for循环内部,仔细看看这部分:
// If it's a blank line
if rgxRoot.MatchString(linetext) {
rule := &Section{} // Notice the `:=`
rule.Category = linetext
}
您基本上是rule在 that 范围内创建一个新变量if,而您可能想重用已在for循环外创建的变量。
因此,尝试将其更改为:
// If it's a blank line
if rgxRoot.MatchString(linetext) {
rule = &Section{} // Notice the `=`
rule.Category = linetext
}
- 1 回答
- 0 关注
- 175 浏览
添加回答
举报
0/150
提交
取消