如何从Markdown中提取链接

Keanu73:

我正在尝试解析可能是超链接或markdown中的超链接的输入。我可以轻松地检查它是否是超链接^https?://.+$并使用regexp.Match,但是对于markdown链接,它对我来说是一个完全不同的兔子洞。

我遇到了这个正则表达式^\[([\w\s\d]+)\]\((https?:\/\/[\w\d./?=#]+)\)$,我试图对其进行修改以匹配markdown链接,但是在由于某种原因捕获了最后一个括号之后,我一直在寻找仅匹配第二个捕获组,链接以及诸如SubexpNames,FindStringIndex之类的东西。 ,FindSubmatch,Split等,但它们似乎都无法捕捉到我正在寻找的内容(有时它们仍会返回整个字符串)或很可能是我做错了。

这是我要找的东西:

Input - [https://imgur.com/abc](https://imgur.com/bcd)
Should output the link - https://imgur.com/bcd

到目前为止,这是我的代码:https : //play.golang.org/p/OiJE3TvvVb6

威克多·史翠比维(WiktorStribiżew):

您可以regexp.FindStringSubmatch用来获取由单个URL验证的正则表达式产生的捕获值:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    markdownRegex := regexp.MustCompile(`^\[[^][]+]\((https?://[^()]+)\)$`)
    results := markdownRegex.FindStringSubmatch("[https://imgur.com/abc](https://imgur.com/bcd)")
    fmt.Printf("%q", results[1])
}

在线观看GO演示

您可以考虑使用regexp.FindAllStringSubmatch查找所需链接的所有匹配项:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    markdownRegex := regexp.MustCompile(`\[[^][]+]\((https?://[^()]+)\)`)
    results := markdownRegex.FindAllStringSubmatch("[https://imgur.com/abc](https://imgur.com/bcd) and [https://imgur.com/xyy](https://imgur.com/xyz)", -1)
    for v := range results {fmt.Printf("%q\n", results[v][1])}
}

观看Go lang演示

该模式表示:

  • \[-一个[字符
  • [^][]+-除[以外的1+个字符]
  • ]\(- ](子串
  • (https?://[^()]+)-第1组:http,则可选的s,则://子串,然后比其他1+字符()
  • \)-一个)字符

请参阅在线正则表达式演示

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章