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.
Code
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
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.PII Text CensorDetect and redact emails, phone numbers, credit card numbers, and US Social Security numbers in text, reporting how many of each were masked.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.
FAQ
- How do you run Regexp ReplaceAllFunc Match Callback?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.