Fragment Description:



Inserting html tag into a string using regexp.ReplaceAllStringFunc().
See function which has an apparent difficult signature:
func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte is remarkably simple to use and will help producing powerful strings/runes manipulations.


replaceAllStringFuncInjectHTML

Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:34

/* ... <== see fragment description ... */

package main

import (
    "fmt"
    "regexp"
)

var source = `Channels: The flow of data between send/receive channels must be managed
precisely, to avoid unpleasant deadlocks.
It’s surprisingly easy to start goroutines and use channels.
It isn’t quite as easy to orchestrate their cleanup.
Avoiding deadlocks is also challenging.
Most often this boils down to an ordering problem,
where a goroutine receiving on a go-chan exits
before the upstream goroutines sending on it.
Try to modify the ordering of code in the main()...`

func main() {
    r := regexp.MustCompile(`(\.|:)\s+|(\.{1,3})`)
    newString := r.ReplaceAllStringFunc(source, func(m string) string {
        match := string(r.Find([]byte(m)))
        fmt.Printf(" %q ,", match)
        return r.ReplaceAllString(m, "$1$2 <br>")
    })
    newString = fmt.Sprintf("<br>%s", newString)
    fmt.Printf("\n=====\n%s\n", newString)
}

/* Expected Output:
 ": " , ".\n" , ".\n" , ".\n" , ".\n" , ".\n" , "..." ,
=====
<br>Channels: <br>The flow of data between send/receive channels must be managed
precisely, to avoid unpleasant deadlocks. <br>It’s surprisingly easy to start goroutines and use channels. <br>It isn’t quite as easy to orchestrate their cleanup. <br>Avoiding deadlocks is also challenging. <br>Most often this boils down to an ordering problem,
where a goroutine receiving on a go-chan exits
before the upstream goroutines sending on it. <br>Try to modify the ordering of code in the main()... <br>
*/



Comments