Categorygithub.com/icholy/replace
modulepackage
0.6.0
Repository: https://github.com/icholy/replace.git
Documentation: pkg.go.dev

# README

Streaming text replacement

GoDoc

This package provides a x/text/transform.Transformer implementation that replaces text

Example

package main

import (
	"io"
	"os"
	"regexp"

	"github.com/icholy/replace"
)

func main() {
	f, _ := os.Open("file")
	defer f.Close()

	r := replace.Chain(f,
		// simple replace
		replace.String("foo", "bar"),
		replace.Bytes([]byte("thing"), []byte("test")),

		// remove all words that start with baz
		replace.Regexp(regexp.MustCompile(`baz\w*`), nil),

		// surround all words with parentheses
		replace.RegexpString(regexp.MustCompile(`\w+`), "($0)"),

		// increment all numbers
		replace.RegexpStringFunc(regexp.MustCompile(`\d+`), func(match string) string {
			x, _ := strconv.Atoi(match)
			return strconv.Itoa(x+1)
		}),
	)

	_, _ = io.Copy(os.Stdout, r)
}

Notes Regexp* functions

  • RegexpTransformer is stateful and cannot be used concurrently.
  • The replace functions should not save or modify any []byte parameters they recieve.
  • If a match is longer than MaxMatchSize it may be skipped (Default 2kb).
  • For better performance, reduce the MaxMatchSize size to the largest possible match.
  • Do not use with transform.Chain, see https://github.com/golang/go/issues/49117.

# Packages

No description provided by the author

# Functions

Bytes returns a transformer that replaces all instances of old with new.
Chain returns a reader which applies all provided transformers.
Regexp returns a transformer that replaces all matches of re with new.
RegexpFunc returns a transformer that replaces all matches of re with the result of calling replace with the match.
RegexpIndexFunc returns a transformer that replaces all matches of re with the return value of replace.
RegexpString returns a transformer that replaces all matches of re with template Inside template, $ signs are interpreted as in Expand, so for instance $1 represents the text of the first submatch.
RegexpStringFunc returns a transformer that replaces all matches of re with the result of calling replace with the match.
RegexpStringSubmatchFunc returns a transformer that replaces all matches of re with the result of calling replace with the submatch.
RegexpSubmatchFunc returns a transformer that replaces all matches of re with the result of calling replace with the submatch.
String returns a transformer that replaces all instances of old with new.

# Structs

RegexpTransformer replaces regexp matches in a stream See: http://golang.org/x/text/transform Note: this Transformer is not safe for concurrent use.
Transformer replaces text in a stream See: http://golang.org/x/text/transform.