我正在尝试解析可能是超链接或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])
}
您可以考虑使用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])}
}
该模式表示:
\[
-一个[
字符[^][]+
-除[
和以外的1+个字符]
]\(
- ](
子串(https?://[^()]+)
-第1组:http
,则可选的s
,则://
子串,然后比其他1+字符(
和)
\)
-一个)
字符请参阅在线正则表达式演示。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句