Search code examples
regexgomarkup

Replace specific new lines starting with " #" in GO


I'm new in GO, and I'm little confused. 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.

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

Solution

  • 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).

    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. Here's a playground for go where I have tested the code.