python - 如何检查 Markdown 中的键值元数据

标签 python markdown

我需要检查使用 markdown 格式化的输入是否在开头具有键值对元数据,然后在整个元数据 block 之后插入文本。

我在第一行中查找 :,如果找到,则在第一个换行符处拆分输入字符串并添加我的内容。

现在,if markdown_content.splitlines()[0].find(':') >= 0: 显然会失败,因为开头没有元数据,但其他内容包含 :相反。

示例

输入元数据:

page title: fancypagetitle
something else: another value

# Heading

Text

不带元数据的输入,但带有:

This is a [link](http://www.stackoverflow.com)

# Heading

Text

我的问题是:如何检查元数据 block 是否存在,如果存在,则在元数据和剩余的 Markdown 之间添加一些内容。

元数据的定义

The keywords are case-insensitive and may consist of letters, numbers, underscores and dashes and must end with a colon. The values consist of anything following the colon on the line and may even be blank.

If a line is indented by 4 or more spaces, that line is assumed to be an additional line of the value for the previous keyword. A keyword may have as many lines as desired.

The first blank line ends all meta-data for the document. Therefore, the first line of a document must not be blank. All meta-data is stripped from the document prior to any further processing by Markdown.

来源:https://pythonhosted.org/Markdown/extensions/meta_data.html

最佳答案

您是否考虑过查看元数据扩展的源代码以了解它是如何完成的?

regex使用的是:

META_RE = re.compile(r'^[ ]{0,3}(?P<key>[A-Za-z0-9_-]+):\s*(?P<value>.*)')

当然还有regex对于辅助线:

META_MORE_RE = re.compile(r'^[ ]{4,}(?P<value>.*)')

如果您注意到,这些正则表达式比您的更具体,并且匹配误报的可能性要小得多。然后扩展将文档分割成行,loops遍历每一行与这些正则表达式进行比较,并在不匹配的第一行(可能是空行,也可能不是空行)上跳出循环。

如果您注意到该代码中,有一个 new feature已添加,将在下一版本中提供。添加了对可选 YAML 样式分隔符的支持。如果您习惯使用最新(未发布)的开发代码,则可以将元数据包装在 YAML 分隔符中,这可能会使找到元数据的结尾变得更容易。

例如,上面的示例文档将如下所示(请注意,我使用了可选的结束特定分隔符( ... ),它更清楚地标记了结束):

---
page title: fancypagetitle
something else: another value
...

# Heading

Text

也就是说,您仍然需要小心,不要得到错误的匹配(例如 <hr>)。我想无论哪种方式,您都确实需要根据自己的需要重新实现元数据扩展中的所有内容。当然,它是开源的,所以只要你遵守 license 就可以.

抱歉,但我无法确定下一次发布的具体时间。

哦,查看 MultiMarkdown 提供的此功能的描述也可能会有所帮助。这启发了 Python-Markdown 中的功能。这可能会让您更清楚地了解元数据的组成部分。

关于python - 如何检查 Markdown 中的键值元数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27962800/

相关文章:

python - python中的len()和sys.getsizeof()方法有什么区别?

python - 匹配正则表达式中的连续数字,同时忽略 python3 中的破折号

python - Pandas 按季度重新采样,并显示开始和结束月份

python - Python 中二维凸包的周长

python - 如何从 python 脚本中的 shell 脚本返回值

ruby-on-rails - 多部分电子邮件的 Markdown 为文本/纯文本和文本/html

javascript - reveal.js 中的片段使用 Markdown

youtube - Bookdown中的youtube链接

ios - 在 Swift 中将 Markdown 格式的字符串转换为 NSAttributedString

reactjs - React MDX Markdown 文件中的引用 Frontmatter