4

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

2 Answers 2

11

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/"]
}
Sign up to request clarification or add additional context in comments.

Comments

2

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?

"<a href="$0">$0</a>"

3 Comments

i solved it using \\, but the core problem is like you said (using double-quotes), so using back-ticks is what i need, thanks. what do you mean with (how did you expect this to work?), what's wrong, i give the output that i want
This "<a href="$0">$0</a>" is a string literal "<a href=", followed by $0 (which means nothing in Go), followed by the string ">$0</a>". If you're going to use double-quotes, then you can't use double quotes inside of the string, unless you escape them.
right, i already changed it to '<a href="$0" targe="_blank" rel="nofollow">$0</a>', thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.