go
32 lines · 7 steps
Extracting delimited text with strings.Cut
Two helpers pull the text between an opening and closing delimiter using Go's strings.Cut for clean, allocation-light slicing.
Explained by
highlit
1package textutil
2
3import "strings"
4
5func ExtractBetween(s, open, close string) (string, bool) {
6 _, after, found := strings.Cut(s, open)
7 if !found {
8 return "", false
9 }
10 before, _, found := strings.Cut(after, close)
11 if !found {
12 return "", false
13 }
14 return before, true
15}
16
17func ExtractAll(s, open, close string) []string {
18 var matches []string
19 for {
20 _, after, found := strings.Cut(s, open)
21 if !found {
22 break
23 }
24 inner, rest, found := strings.Cut(after, close)
25 if !found {
26 break
27 }
28 matches = append(matches, inner)
29 s = rest
30 }
31 return matches
32}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1strings.Cut returns the text before and after the first separator plus a found flag, avoiding manual index math.
- 2Checking the found boolean at each cut keeps parsing safe when a delimiter is missing.
- 3Reassigning the remaining tail in a loop turns a single-match helper into a find-all scanner.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/extracting-delimited-text-with-strings-cut-explained-go-9634/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.