我正在尝试解析可能是超链接或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
最佳答案
您可以使用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
该模式表示:
\[
-一个[
char [^][]+
-[
和]
之外的1个以上字符]\(
-](
子字符串(https?://[^()]+)
-组1:http
,然后是可选s
,然后是://
子字符串,然后是(
和)
以外的1+个字符\)
-一个)
字符。 参见online regex demo。
关于regex - 如何从Markdown中提取链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60464033/