【发布时间】:2020-12-13 01:26:50
【问题描述】:
我目前正在尝试在 django/python 中解析 markdown 并链接主题标签。有一些简单的解决方案:
for tag in re.findall(r"(#[\d\w\.]+)", markdown):
text_tag = tag.replace('#', '')
markdown = markdown.replace(
tag,
f"[{tag}](/blog/?q=%23{text_tag})")
这很好用,但会将带有# 的所有内容转换为链接。例如:
https://example.com/xyz/#section-on-page 被链接。如果它当前位于链接本身内部,它也会被链接化。
随着链接被链接化,内部链接也会被破坏。
这是一个综合案例:
#hello This is an #example of some text with #hash-tags - http://www.example.com/#not-hashtag but dont want the link
#hello #goodbye #summer
#helloagain
#goodbye
This is #cool, yes it is #radaf! I like this #tool.
[Link](#not-a-hashtag)
[Link](https://example/#also-not)
<a href="#this-neither">Hai</a>
谢谢
【问题讨论】:
-
"注意:请求 HTML、JSON 等正则表达式往往会遇到负面反应。如果有解析器,请改用它" - 正则表达式标记
-
我目前正在使用 misune 解析器。当前没有具有标签链接的解析器。我正在自己编写链接器作为模板过滤器。
标签: python django regex markdown