SplitAfter Keeps Trailing Delimiters

Split log lines and paths with strings.SplitAfter so each returned segment retains its delimiter, making it easy to re-emit the original text exactly.

GoCli Tooling

Code

gosnippet
23 lines
package main

import (
	"fmt"
	"strings"
)

func main() {
	line := "GET /api/v1/users;POST /api/v1/orders;DELETE /api/v1/orders/7;"

	// SplitAfter:每段带上分隔符,拼回去就是原文
	segments := strings.SplitAfter(line, ";")
	for i, segment := range segments {
		if segment == "" {
			continue
		}
		fmt.Printf("segment %d: %q\n", i, segment)
	}
	fmt.Println("rejoined equals original:", strings.Join(segments, "") == line)

	// 对照:Split 丢掉分隔符
	fmt.Println("plain Split:", strings.Split(line, ";"))
}

How execution unfolds

SplitAfter Keeps Trailing Delimiters comes down to the function main.

Repetition is confined to for i, segment := range segments — the rest of the file is straight-line.

Putting it to use

The demo output is labeled (segment, rejoined equals original:, plain Split:), so every printed line maps back to its originating operation.

Core lines

for i, segment := range segments {
	if segment == "" {
		continue
	}
	fmt.Printf("segment %d: %q\n", i, segment)
}

Interactive Tools for This Topic

FAQ

What does SplitAfter Keeps Trailing Delimiters print when run?
No setup needed: run the file and look for labeled lines like `segment`, `rejoined equals original:`, `plain Split:` in the output.