英文:
Regexp replacement string, what am I doing wrong?
问题
我正在构建一个简单的 Markdown 到 HTML 解析器,但是我的正则表达式替换无法正常工作。我做错了什么?
我尝试了多种不同的变体和搜索,但仍然无法正确工作。
Markdown:
# Hello World!
代码:
content, readErr := ioutil.ReadFile(markdownFile)
contentString := string(content)
h1 := regexp.MustCompile(`^#(.*)`)
contentHTML := h1.ReplaceAllStrings(contentString, `<h1>$1</h1>`)
fmt.Println(contentHTML)
期望输出:
<h1>Hello World!</h1>
实际输出:
</h1>Hello World!
我确定这是一个简单的错误,但我不知道为什么会得到这样的输出。
英文:
I am building a simple markdown to html parser and I cannot get my regular expression replacement to work. What am I doing wrong?
I have tried multiple different variations and googling but still can't get it to work properly.
Markdown:
# Hello World!
Code:
content, readErr := ioutil.ReadFile(markdownFile)
contentString := string(content)
h1 := regexp.MustCompile(`^#(.*)`)
contentHTML := h1.ReplaceAllStrings(contentString, `<h1>$1</h1>`)
fmt.Println(contentHTML)
Expected Output:
<h1>Hello World!</h1>
Actual Output:
</h1>Hello World!
I'm sure its a simple mistake but I am at a lose for how I am getting the output that I am.
答案1
得分: 0
当我修复ReplaceAllString
方法时,它正常工作:
package main
import (
"fmt"
"regexp"
)
func main() {
contentString := "# Hello World!"
h1 := regexp.MustCompile(`^#(.*)`)
contentHTML := h1.ReplaceAllString(contentString, `<h1>$1</h1>`)
fmt.Println(contentHTML)
}
输出结果:
<h1> Hello World!</h1>
注意:
- 你的正则表达式捕获了
#
后面的空格,这可能不是你真正想要的。考虑将其更改为类似^#\s+(.*)
的形式。 - 通常,使用正则表达式将一种格式转换为另一种格式容易出错,并且可能导致非常复杂的代码。对于简单的练习来说还可以,但在生产环境中不要这样做
英文:
When I fix the ReplaceAllString
method, it works just fine:
package main
import (
"fmt"
"regexp"
)
func main() {
contentString := "# Hello World!"
h1 := regexp.MustCompile(`^#(.*)`)
contentHTML := h1.ReplaceAllString(contentString, `<h1>$1</h1>`)
fmt.Println(contentHTML)
}
Prints:
<h1> Hello World!</h1>
Notes:
- Your regexp captures the whitespace following the
#
, which you probably don't really want. Consider changing it to something like^#\s+(.*)
. - Generally, converting from one format to another using regexps is rather error-prone and may result in very complicated code. For a simple exercise it's fine, but don't do this in production
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论