Regexp ReplaceAllFunc Match Callback

Redact and mask each match through a ReplaceAllStringFunc callback, since replacement templates cannot run per-match logic like length-based masking.

GoData Integrity

Code

gosnippet
29 lines
package main

import (
	"fmt"
	"regexp"
	"strings"
)

func main() {
	logLine := "user=alice action=deploy 42 files token=sk-9f8e7d6c5b4a"

	// $1 模板只能做静态改写;按内容计算的改写走 ReplaceAllStringFunc callback 回调
	tokenRe := regexp.MustCompile("token=[A-Za-z0-9-]+")
	redacted := tokenRe.ReplaceAllStringFunc(logLine, func(string) string {
		return "token=[REDACTED]"
	})
	fmt.Println(redacted)

	// 回调收到的是完整匹配字符串 match,其长度可参与计算
	countRe := regexp.MustCompile("[0-9]+")
	masked := countRe.ReplaceAllStringFunc(redacted, func(m string) string {
		return strings.Repeat("*", len(m))
	})
	fmt.Println(masked)

	// 模板版对比:同样替换 token 值,模板只能引用捕获组
	prefixRe := regexp.MustCompile("(token=)[A-Za-z0-9-]+")
	fmt.Println(prefixRe.ReplaceAllString(logLine, "$1***"))
}

How the logic is laid out

Structurally, expect the function main and nothing else.

Caveats

  • Every call goes to the standard library — copy it in and it works.

Putting it to use

Entry signature: func main()

Core lines

return strings.Repeat("*", len(m))
return "token=[REDACTED]"

Interactive Tools for This Topic

FAQ

How do you run Regexp ReplaceAllFunc Match Callback?
Execute it straight away — the program needs nothing beyond the runtime.