Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
145: Regex Capture Groups in Go
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:
- 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).
- Iterate through the slice and use
FindStringSubmatchto extract these two pieces of information. - Print the results in the format:
Version: 1, Resource: users. - Ensure your code gracefully ignores strings that do not match the pattern (like "invalid-url") without crashing.
There are no comments for now.