Skip to Content
Course content

47: Regular Expressions in Go

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

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) []string that finds all occurrences of version numbers in a given block of text.
  • Use FindAllString to 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."
Rating
0 0

There are no comments for now.

to be the first to leave a comment.