FieldsFunc Splits On Custom Boundaries
Split text on any rune class with strings.FieldsFunc so comma, semicolon, and whitespace delimiters collapse without empty fields.
Code
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
line := "alpha,beta;gamma delta\tepsilon|zeta"
// FieldsFunc:任意 rune 返回 true 即视为分隔符
parts := strings.FieldsFunc(line, func(r rune) bool {
return r == ',' || r == ';' || r == '|' || unicode.IsSpace(r)
})
fmt.Println("parts:", parts, "| count:", len(parts))
// 连续分隔符不会产生空字段,与 Split 的行为不同
padded := ",,a;;b||"
cleaned := strings.FieldsFunc(padded, func(r rune) bool {
return r == ',' || r == ';' || r == '|'
})
fmt.Println("cleaned:", cleaned)
// 按数字边界切分,只保留字母段
words := strings.FieldsFunc("ab12cd345ef", func(r rune) bool {
return unicode.IsDigit(r)
})
fmt.Println("letters:", words)
// 对照:Fields 只按空白切分
fmt.Println("fields:", len(strings.Fields(line)), "fieldsFunc:", len(parts))
}How the logic flows
FieldsFunc Splits On Custom Boundaries reduces to the function main.
Applying it
Running the file prints labeled results such as parts:, cleaned:, letters: — each operation’s effect is visible in the output.
Statements that matter
return r == ',' || r == ';' || r == '|' || unicode.IsSpace(r)
return unicode.IsDigit(r)
Interactive Tools for This Topic
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.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does FieldsFunc Splits On Custom Boundaries print when run?
- Run it as a complete program — the output lines carry labels such as `parts:`, `cleaned:`, `letters:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.