【问题标题】:How to extract links from markdown如何从markdown中提取链接
【发布时间】:2020-06-13 06:49:36
【问题描述】:

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

我遇到了这个正则表达式 ^\[([\w\s\d]+)\]\((https?:\/\/[\w\d./?=#]+)\)$,我试图修改它以匹配 only 降价链接,但是在由于某种原因捕获了最后一个括号之后,我一直在寻找匹配第二个捕获组,链接,包含 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

【问题讨论】:

  • 为什么需要正则表达式?只需检查第一个字符是否为[
  • 只是为了检查它是否是一个有效的http链接,然后最好我想从markdown链接中解析链接本身
  • 你在做什么解析?
  • 基本上我正在接受输入,可能是超链接或降价链接,然后我将链接嵌入到其他地方,并在另一个字符串上使用 ReplaceAll。 ``` toEdit = *[THE LINK TO THE TEMPLATE](%LINK%)* toEdit = strings.ReplaceAll(toEdit, "%LINK%", link) ``
  • 请记住,如果您的描述中有括号,则可能会中断。 IE。 [Foo (bar)](http://example.com/) 会坏掉。这是正则表达式对于这样的工作来说是错误的工具的原因之一。最好的解决方案是使用适当的 Markdown 解析器。

标签: regex go hyperlink markdown


【解决方案1】:

您可以使用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 demo online

您可以考虑使用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 demo

图案的意思:

  • \[ - 一个 [ 字符
  • [^][]+ - 除了 [] 之外的 1+ 个字符
  • ]\( - ]( 子字符串
  • (https?://[^()]+) - 第 1 组:http,然后是可选的 s,然后是 :// 子字符串,然后是除 () 之外的 1+ 个字符
  • \) - ) 字符。

请参阅online regex demo

【讨论】:

    猜你喜欢
    • 2019-07-10
    • 2015-10-29
    • 2023-03-03
    • 1970-01-01
    • 2012-08-04
    • 2022-08-02
    • 2011-06-04
    • 1970-01-01
    相关资源
    最近更新 更多