簡體   English   中英

在GO中替換以“#”開頭的特定新行

[英]Replace specific new lines starting with “ #” in GO

我是GO的新手,我有點困惑。 我不知道我在做什么錯。

我想將markdown轉換為html,所以我需要找到每行以空格和#開頭的行,並替換為h1標簽。

如果我測試多行,則無法正常工作,而僅測試一行時,則可以正常工作。

例:

//this works
    testtext := "#Some text"
    expectedResult := "<h1>Some text</h1>"

//this fails
    testtext :=`#test
                ##test2
                ####test4
                ###test3`
    expectedResult := `<h1>test</h1>
                       ##test
                       ####test
                       ###test`
//test
    func TestReplaceHedding1(t *testing.T) {
        text := `#test
                ##test2
                ####test4
                ###test3`
        replaceHedding1(&text)

        if text != "<h1>test</h1>##test\n####test\n###test" {
            t.Errorf("expected <h1>test</h1>, got", text)
        }
    }

    func replaceHedding1(Text *string) {
        reg := regexp.MustCompile(`^\s*#{1}(.*?)$`)
        *Text = reg.ReplaceAllString(*Text, "<h1>$1</h1>")
    }

好吧,您的正則表達式應該更像這樣:

(?m)^\s*#([^#].*?)$

(?m)使^$匹配行的每個開頭和結尾,因為否則,它們匹配字符串的開頭和結尾(我也刪除了{1}因為它是多余的)。

然后,我在捕獲組中添加了[^#] ,以確保第一個#之后的下一個字符不是另一個#

我還更改了您的測試字符串,並使用了雙引號和\\n因為當您使用反引號時, #之前的空格變為文字,而if則將隨后失敗。 這是我測試代碼游樂場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM