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
47: Regular Expressions in Go
I've seen this exact snippet in a dozen code reviews over the years. Usually, it's written by someone who knows regex well from Python or JavaScript but hasn't quite grasped how Go handles the regexp package. Take a look at this log-parsing function:
func ParseLogLine(line string) bool {
// We want to check if the line contains an ERROR level tag
match, _ := regexp.MatchString(`^\[ERROR\]\s+(.*)$`, line)
return match
}
func main() {
logs := []string{"[INFO] System start", "[ERROR] Database connection failed", "[INFO] Heartbeat"}
for _, log := range logs {
if ParseLogLine(log) {
fmt.Println("Found error!")
}
}
}
At first glance, it works. If you run it, it finds the error. But if you're running this against a production log file with ten million lines, your CPU is going to scream. Why? Because regexp.MatchString compiles the regular expression every single time the function is called. Compiling a regex is an expensive operation; doing it inside a loop is a cardinal sin in Go.
Stop the Re-compilation Cycle
The fix is to compile your regular expression once and reuse it. In Go, we usually do this at the package level using regexp.MustCompile. The "Must" prefix is a convention in Go: it means the function will panic if the regex is invalid. Since your regex is usually a hardcoded constant, a panic at startup is actually preferable to a silent failure at runtime.
var errorRegex = regexp.MustCompile(`^\[ERROR\]\s+(.*)$`)
func ParseLogLine(line string) bool {
return errorRegex.MatchString(line)
}
Now, the regex is compiled into a machine-state once when the program starts. Every call to ParseLogLine now just executes that pre-compiled state against the input string. It's orders of magnitude faster.
Actually Getting the Data Out
Checking if a string matches is fine, but usually, you actually want the data inside the parentheses—the "capture groups." MatchString only gives you a boolean. To get the actual content, you'll want FindStringSubmatch.
Here is where it gets slightly tricky. FindStringSubmatch returns a slice of strings. The first element (index 0) is always the entire match. The subsequent elements are your capture groups. If you forget this, you'll end up printing the [ERROR] prefix instead of the actual error message.
func ExtractErrorMessage(line string) string {
matches := errorRegex.FindStringSubmatch(line)
if len(matches) < 2 {
return "" // No match or no capture group
}
return matches[1] // The first group (.*)
}
Dealing with the RE2 Limitation
You might try to use a "lookahead" or "lookbehind" (like (?=...)) if you're coming from Perl or PCRE. Stop right there. Go uses the RE2 engine, which is intentionally designed to run in linear time. To guarantee this performance and prevent "catastrophic backtracking" (which can be used for ReDoS attacks), Go does not support look-around assertions.
If you find yourself needing a lookahead, you have two choices: either restructure your regex to capture more than you need and then trim the result in Go code, or use a more complex series of strings.Contains and strings.Index calls. Trust me, often the "manual" string manipulation is clearer and faster anyway.
📋 Practical Task
Build a Version Number Extractor
You've been tasked with writing a utility that scans a list of software release notes and extracts the semantic version numbers (e.g., "v1.2.3" or "2.0.11").
Requirements:
- Create a package-level pre-compiled regular expression that identifies version strings. The pattern should support an optional 'v' prefix, followed by three sets of numbers separated by dots (Major.Minor.Patch).
- Write a function
ExtractVersions(input string) []stringthat finds all occurrences of version numbers in a given block of text. - Use
FindAllStringto retrieve the matches. - Test your function with a string like:
"Updating from v1.0.4 to 1.1.0, but we skipped 1.0.9 for stability."
There are no comments for now.