【问题标题】:Creating a linked hashtag in markdown在 Markdown 中创建链接的主题标签
【发布时间】: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


【解决方案1】:

使用

def regex_replace(m):
    if m.group(1):
        return fr"[{m.group(1)}](/blog/?q=%23{m.group(2)})"
    return m.group()

regex = r'''<[^>]*>|\[[^][]*]\([^()]*\)|https?://[^\s"'<>]*|(#(\w+(?:\.\w+)*))'''
markdown = re.sub(regex, regex_replace, markdown)

Python code

&lt;[^&gt;]*&gt;|\[[^][]*]\([^()]*\)|https?://[^\s"'&lt;&gt;]*|(#(\w+(?:\.\w+)*)) 是一个正则表达式,匹配一个标签、降价链接、URL 或匹配一个主题标签,将其作为一个整体及其在#(第 2 组)之后的部分(第 1 组)捕获。匹配第一组后,替换为链接的主题标签,否则返回字符串而不进行修改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    相关资源
    最近更新 更多