简体   繁体   English

在GO中替换以“#”开头的特定新行

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

I'm new in GO, and I'm little confused. 我是GO的新手,我有点困惑。 I don't know what i'm doing wrong. 我不知道我在做什么错。

I want to convert markdown to html, so I need to find each line which starts with space and #, and replace with h1 tag. 我想将markdown转换为html,所以我需要找到每行以空格和#开头的行,并替换为h1标签。

If I test for multiple lines it's not working but when I test just with one line it's working. 如果我测试多行,则无法正常工作,而仅测试一行时,则可以正常工作。

Example: 例:

//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>")
    }

Well, your regex should be more like this: 好吧,您的正则表达式应该更像这样:

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

The (?m) makes ^ and $ match every beginning and end of line respectively, because otherwise, they match the beginning and end of string (I have also removed {1} since it is redundant). (?m)使^$匹配行的每个开头和结尾,因为否则,它们匹配字符串的开头和结尾(我也删除了{1}因为它是多余的)。

I then added [^#] inside the capture group to ensure that the next character after the first # is not another # . 然后,我在捕获组中添加了[^#] ,以确保第一个#之后的下一个字符不是另一个#

I have also changed your test string and used double quotes and \\n because when you use backticks, the spaces before the # become literal and your if will subsequently fail. 我还更改了您的测试字符串,并使用了双引号和\\n因为当您使用反引号时, #之前的空格变为文字,而if则将随后失败。 Here's a playground for go where I have tested the code . 这是我测试代码游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM