gpt4 book ai didi

regex - 在 GO 中替换以 "#"开头的特定新行

转载 作者:IT王子 更新时间:2023-10-29 01:37:02 26 4
gpt4 key购买 nike

我是 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 随后会失败。这是一个 playground for go where I have tested the code .

关于regex - 在 GO 中替换以 "#"开头的特定新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23629556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com