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

Walkthrough

Space play step click any line
Three takeaways
  1. 1strings.Cut returns the text before and after the first separator plus a found flag, avoiding manual index math.
  2. 2Checking the found boolean at each cut keeps parsing safe when a delimiter is missing.
  3. 3Reassigning the remaining tail in a loop turns a single-match helper into a find-all scanner.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Extracting delimited text with strings.Cut — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code