typestar

Regular expressions in Go

Compile once, reuse; named groups make the match readable.

var logLine = regexp.MustCompile(
    `^(?P<level>[A-Z]+)\s+(?P<logger>[\w.]+):\s+(?P<message>.*)$`)

func parseLine(line string) (map[string]string, bool) {
    match := logLine.FindStringSubmatch(line)
    if match == nil {
        return nil, false
    }
    fields := make(map[string]string, len(match)-1)
    for i, name := range logLine.SubexpNames() {
        if i > 0 && name != "" {
            fields[name] = match[i]
        }
    }
    return fields, true
}

func replaceAll(text string) string {
    digits := regexp.MustCompile(`\d+`)
    return digits.ReplaceAllString(text, "N")
}

How it works

  1. MustCompile at package level, for patterns you control.
  2. FindStringSubmatch returns the whole match then the groups.
  3. SubexpIndex finds a named group without counting.

Keywords and builtins used here

The run, in numbers

Lines
21
Characters to type
520
Tokens
123
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 70 seconds.

Type this snippet

Step 5 of 5 in Collections & text, step 13 of 26 in Standard library & project layout.

← Previous Next →

Regular expressions in other languages