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 |
|
|
|
Zero or more |
|
|
|
One or more |
|
|
|
Zero or one |
|
|
|
Character class |
|
|
|
Start of string |
|
|
|
End of string |
|
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

