【发布时间】:2015-08-24 10:14:46
【问题描述】:
我正在尝试从 Markdown 中提取锚文本和相关 URL。我见过this 的问题。不幸的是,answer 似乎没有完全回答我想要的。
在 Markdown 中,插入链接有两种方式:
示例 1:
[anchor text](http://my.url)
示例 2:
[anchor text][2]
[1]: http://my.url
我的脚本是这样的(注意我使用的是regex,而不是re):
import regex
body_markdown = "This is an [inline link](http://google.com). This is a [non inline link][4]\r\n\r\n [1]: http://yahoo.com"
rex = """(?|(?<txt>(?<url>(?:ht|f)tps?://\S+(?<=\P{P})))|\(([^)]+)\)\[(\g<url>)\])"""
pattern = regex.compile(rex)
matches = regex.findall(pattern, body_markdown, overlapped=True)
for m in matches:
print m
这会产生输出:
('http://google.com', 'http://google.com')
('http://yahoo.com', 'http://yahoo.com')
我的预期输出是:
('inline link', 'http://google.com')
('non inline link', 'http://yahoo.com')
如何从 Markdown 中正确捕获锚文本?
【问题讨论】: