golang regex to find urls in a string

huangapple go评论83阅读模式
英文:

golang regex to find urls in a string

问题

我正在尝试在字符串中找到所有的链接,并将它们转换为超链接,就像这个 JavaScript 库 https://github.com/bryanwoods/autolink-js

我尝试使用了很多正则表达式,但总是遇到太多错误 http://play.golang.org/p/iQiccXvFiB。我不知道 Go 语言是否有不同的正则表达式语法。

所以,有没有适用于 Go 语言的正则表达式可以很好地匹配字符串中的 URL?

谢谢。

英文:

I am tring to find all links in a string and then hyperlink them
like this js lib https://github.com/bryanwoods/autolink-js

i tried to use alot of regex but i always got too many errors
http://play.golang.org/p/iQiccXvFiB
i don't know if go has a different regex syntax

so, what regex that works in go that is good to match urls in strings

thanks

答案1

得分: 9

你可以使用xurls

import "mvdan.cc/xurls"

func main() {
    xurls.Relaxed().FindString("Do gophers live in golang.org?")
    // "golang.org"
    xurls.Relaxed().FindAllString("foo.com is http://foo.com/.", -1)
    // ["foo.com", "http://foo.com/"]
    xurls.Strict().FindAllString("foo.com is http://foo.com/.", -1)
    // ["http://foo.com/"]
}
英文:

You can use xurls:

import "mvdan.cc/xurls"

func main() {
        xurls.Relaxed().FindString("Do gophers live in golang.org?")
        // "golang.org"
        xurls.Relaxed().FindAllString("foo.com is http://foo.com/.", -1)
        // ["foo.com", "http://foo.com/"]
        xurls.Strict().FindAllString("foo.com is http://foo.com/.", -1)
        // ["http://foo.com/"]
}

答案2

得分: 2

请使用反引号(`)而不是双引号(")来表示字符串字面值。双引号内的反斜杠会启动转义序列,而在这种情况下您不需要或不希望使用转义序列。

此外,您对这段代码的预期是什么?

`<a href="$0">$0</a>`
英文:

Use back-ticks instead of double-quotes for your string literals. Back-slashes inside double-quotes start escape sequences, which you don't need/want for this use case.

Additionally, how did you expect this to work?

&quot;&lt;a href=&quot;$0&quot;&gt;$0&lt;/a&gt;&quot;

huangapple
  • 本文由 发表于 2014年10月25日 17:47:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/26561149.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定