Skip to Content
Course content

145: Regex Capture Groups in Go

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're sorting through a stack of physical mail. You're looking for invoices, and every invoice has a specific format: a company name, a date, and a total amount. When you find an invoice, you don't just want to know that it's an invoice; you want to extract the specific date and the dollar amount to put into your spreadsheet. You aren't interested in the "Invoice #" label or the address—you just want the specific values inside those sections.

In Go, a standard regex match is like identifying the whole envelope. Capture groups are like taking a highlighter and circling only the specific bits of text you actually want to use in your code. By wrapping parts of your regular expression in parentheses (), you're telling Go: "Yes, match the whole pattern, but keep these specific pieces in a separate bucket for me."

The Magic of Parentheses

Let's say we're processing a set of custom Order IDs that look like this: ORD-2023-XJ99. We need to extract the year and the unique ID separately. If we just used a normal match, we'd get the whole string. To get the pieces, we use parentheses.

package main

import (
	"fmt"
	"regexp"
)

func main() {
	text := "Your order number is ORD-2023-XJ99"
	// We wrap the year and the ID in parentheses to create capture groups
	re := regexp.MustCompile(`ORD-(\d{4})-([A-Z0-9]+)`)
	
	match := re.FindStringSubmatch(text)
	fmt.Println(match)
}

If you run this, you'll see something interesting in the output: [ORD-2023-XJ99 2023 XJ99]. It's a slice of strings. I've found that developers often get tripped up by the length of this slice the first time they use it.

Why the First Element Always Feels Weird

You'll notice the resulting slice has three elements, even though we only defined two sets of parentheses. This is a quirk of how almost all regex engines work, including Go's.

  • match[0] is always the entire match (the whole envelope).
  • match[1] is the first capture group (the year).
  • match[2] is the second capture group (the ID).

I usually recommend immediately assigning these to named variables. It makes your code much more readable and prevents you from accidentally using match[1] when you actually meant the second group. Like this:

if len(match) == 3 {
	year := match[1]
	id := match[2]
	fmt.Printf("Year: %s, ID: %s\n", year, id)
}

Handling Multiple Matches in One String

What if your string has five different Order IDs and you need all of them? FindStringSubmatch only finds the first occurrence. To get everything, you'll want FindAllStringSubmatch.

Be careful here: this returns a slice of slices ([][]string). Each inner slice follows the same rule: index 0 is the full match, and the subsequent indices are the capture groups. I've seen plenty of bugs where people forget this nesting and try to access the capture group directly from the top-level slice.

text := "Orders: ORD-2021-AA1, ORD-2022-BB2"
re := regexp.MustCompile(`ORD-(\d{4})-([A-Z0-9]+)`)
allMatches := re.FindAllStringSubmatch(text, -1)

for _, m := range allMatches {
    fmt.Printf("Found Year %s and ID %s\n", m[1], m[2])
}

The -1 argument tells Go to find every single match in the string rather than stopping after a certain number.




📋 Practical Task

Parsing API Endpoint Versioning

You are building a middleware tool that needs to extract the version number and the resource name from a list of API endpoints. The endpoints follow the pattern /v1/users, /v2/payments, or /v14/settings.

Write a Go program that takes the following slice of strings:

endpoints := []string{"/v1/users", "/v2/payments", "/v14/settings", "invalid-url", "/v3/logs"}

Your task is to:

  1. Define a regular expression using capture groups to isolate the version number (the digits after 'v') and the resource name (the text after the second slash).
  2. Iterate through the slice and use FindStringSubmatch to extract these two pieces of information.
  3. Print the results in the format: Version: 1, Resource: users.
  4. Ensure your code gracefully ignores strings that do not match the pattern (like "invalid-url") without crashing.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.