我正在嘗試將一個簡單的降價文件轉換為 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 關注
- 162 瀏覽
添加回答
舉報
0/150
提交
取消