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.
Code
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
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 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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.