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 (

var in = `
This text contains a URL like this:

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

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)
                in, out)


The output of the example looks like this:

This text contains a URL like this:


This text contains a URL like this:

Web links

Copyright © Ben Bullock 2009-2024. All rights reserved. For comments, questions, and corrections, please email Ben Bullock ( or use the discussion group at Google Groups. / Privacy / Disclaimer