liveBook · Manning

Regexp package

As explained in Go in Action, Second Edition

The regexp package is Go's standard-library package for compiling and matching regular expressions.

The regexp package provides Go’s standard-library support for compiled regular expressions, making it useful for validating configuration fields, sanitizing input, and extracting structured data from text. section 10.7

Regular expressions describe sets of strings through literal characters, metacharacters, character classes, and anchors. Go compiles patterns into reusable regexp.Regexp objects and implements RE2 syntax with guaranteed linear-time performance. section 10.7

Common pattern-building elements include:

  • Use . for any character, *, +, and ? for repetition, and [a-z] for character classes. section 10.7
  • Use ^ and $ to require matches at the start and end of a string. section 10.7
  • Append ? to repetition operators to request lazy rather than greedy matching. section 10.7

Validate a configuration name

A configuration validator compiles `^[a-zA-Z0-9_-]+$` with `regexp.MustCompile`, then calls `MatchString` to check that a name contains only alphanumeric characters, hyphens, or underscores. Empty values receive a separate validation error. section 10.7

Table 10.2 Common regular expression metacharacters

Metacharacter

Description

Example

.

Any character

a.c matches “abc”, “a1c”

*

Zero or more

ab*c matches “ac”, “abc”, “abbc”

+

One or more

ab+c matches “abc”, “abbc” (not “ac”)

?

Zero or one

ab?c matches “ac”, “abc”

[a-z]

Character class

[a-z] matches any lowercase letter

^

Start of string

^abc matches “abc” at start only

$

End of string

abc$ matches “abc” at end only

Use the metacharacter reference to compare operators, meanings, and matching examples while constructing patterns. section 10.7

Listing 10.24 Validating configuration fields with regex
import "regexp"

// ValidationError represents a validation error with context
type ValidationError struct {
    Field  string
    Reason string
}

func validateConfig(cfg *Config) []ValidationError {
    var validationErrors []ValidationError

    // Validate name: must be non-empty and alphanumeric with hyphens/underscores
    namePattern := regexp.MustCompile(`^[a-zA-Z0-9_-]+$`) #1
    if cfg.Name == "" {
        validationErrors = append(validationErrors, ValidationError{
            Field:  "name",
            Reason: "cannot be empty",
        })
    }
    if !namePattern.MatchString(cfg.Name) { #2
        validationErrors = append(validationErrors, ValidationError{
            Field:  "name",
            Reason: "must contain only alphanumeric characters, hyphens, or underscores",
        })
    }

    return validationErrors
}

Use the validation listing to trace compiled-pattern setup and matching within a configuration validator. section 10.7

How Go in Action, Second Edition covers it

How deep it goes
Defines core regex syntax and demonstrates compiled matching for one field, while stopping short of a complete syntax catalog.
Examples
Uses metacharacter examples, configuration names, semantic-version strings, hostnames, and a compiled validation listing.
What you can do after
Apply compiled regular expressions to validate configuration values and recognize structured text patterns.
How it connects
Connects regular expressions with configuration validation, input sanitization, text extraction, and string manipulation.

Also explained in

Compare how 2 books explain regexp package →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.