Regexp replace pattern

This is an example Go program illustrating replacing a regular expression containing a pattern.

// Replace "(bug ([0-9]+))" with <a href='http://www.example.org/bug/$2'>$1</a>

package main

import (
        "fmt"
        "regexp"
)

// Test input

var in = `Look at bug 99 and bug 42 for example.`

// Regular expression to match

var bugRegex = "bug\\s+([0-9]+)"

var bugReplace = regexp.MustCompile(bugRegex)

// Replacement text

var urlFmt = "<a href='http://www.example.org/bug/%s'>%s</a>"

func main() {
        // The -1 at the end tells the finder that it doesn't need to limit
        // the number of results.
        var results = bugReplace.FindAllStringSubmatchIndex(in, -1)
        var out = in
        var end = 0
        if len(results) > 0 {
                out = ""
                for num, r := range results {
                        fmt.Println(r)
                        out += in[end:r[0]]
                        bugText := in[r[0]:r[1]]
                        bugNumber := in[r[2]:r[3]]
                        out += fmt.Sprintf(urlFmt, bugNumber, bugText)
                        end = r[1]
                        if num == len(results)-1 {
                                out += in[end:]
                        }
                }
        }
        fmt.Println(out)
}

(download)

The output of the example looks like this:

[8 14 12 14]
[19 25 23 25]
Look at <a href='http://www.example.org/bug/99'>bug 99</a> and <a href='http://www.example.org/bug/42'>bug 42</a> for example.


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