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
MustCompileat package level, for patterns you control.FindStringSubmatchreturns the whole match then the groups.SubexpIndexfinds a named group without counting.
Keywords and builtins used here
boolforfunciflenmakemaprangereturnstringvar
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.
Step 5 of 5 in Collections & text, step 13 of 26 in Standard library & project layout.