Substitute a URL in text using a regular expression

This is an example Go program which demonstrates substituting a URL with a link based on that URL using regular expressions.

package main

import (
        "fmt"
        "regexp"
)

var in = `
This text contains a URL like this: http://www.google.com/
`

var url_comp = "(?:[a-zA-Z0-9]+)"
var url_regex = "https?://(?:" + url_comp + "\\.)*" + url_comp +
        "(?:[0-9]+)?(?:/[^\\s]*)?"

func urlToLink(from []byte) []byte {
        var url = string(from)
        var link = fmt.Sprintf("<a href='%s'>%s</a>", url, url)
        return []byte(link)
}

func main() {
        r := regexp.MustCompile(url_regex)
        out := r.ReplaceAllFunc([]byte(in), urlToLink)
        fmt.Printf("<pre>%s</pre>\n<p>becomes</p>\n<pre>%s</pre>\n",
                in, out)
}

(download)

The output of the example looks like this:

This text contains a URL like this: http://www.google.com/

becomes

This text contains a URL like this: http://www.google.com/

Web links


Copyright © Ben Bullock 2009-2024. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com). / Privacy / Disclaimer