FieldsFunc Splits On Custom Boundaries

Split text on any rune class with strings.FieldsFunc so comma, semicolon, and whitespace delimiters collapse without empty fields.

GoCli Tooling

Code

gosnippet
33 lines
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

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:`.