Skip to content
Go: Distinguish an absent regexp group from an empty match

Go: Distinguish an absent regexp group from an empty match

November 14, 2026

In a small key/value grammar, name and name= can mean different things. Both can yield an empty value string, but submatch indices distinguish an absent optional group from a group that matched zero characters.

Set up

Tested on Linux amd64 with Go 1.26.10. Use Bash with Go on your PATH, a text editor, and the mktemp, rm, and rmdir utilities. The example uses only the standard library. Keep the same terminal through cleanup, and stop if setup fails before saving the source.

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Run the example

Save as go-regexp-optional-group-presence.go:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	pattern := regexp.MustCompile(`^(?P<key>[a-z]+)(?:=(?P<value>[a-z]*))?$`)
	group := pattern.SubexpIndex("value")
	if group < 0 {
		panic("missing named group")
	}
	for _, input := range []string{"name", "name=", "name=green", "name=1"} {
		indices := pattern.FindStringSubmatchIndex(input)
		if indices == nil {
			fmt.Printf("%q: rejected\n", input)
			continue
		}
		start, end := indices[2*group], indices[2*group+1]
		if start < 0 {
			fmt.Printf("%q: value absent\n", input)
		} else {
			fmt.Printf("%q: value present %q\n", input, input[start:end])
		}
	}
	absent := pattern.FindStringSubmatchIndex("name")
	empty := pattern.FindStringSubmatchIndex("name=")
	if absent[2*group] != -1 || empty[2*group] != empty[2*group+1] {
		panic("presence distinction")
	}
}

Run:

go run go-regexp-optional-group-presence.go

Observed output:

"name": value absent
"name=": value present ""
"name=green": value present "green"
"name=1": rejected

Read the result

Each capture uses a pair of indices; group zero describes the entire match. A named group’s number selects its pair without hard-coding the capture position. Negative indices mean the optional group did not participate. Equal nonnegative indices mean it matched an empty string.

Check for no overall match before indexing the result, then check participation before slicing the input. The anchored pattern accepts only the small ASCII grammar shown here.

Apply it carefully

Indices are byte offsets into the original string, even when a pattern matches Unicode text. Keep that same string when slicing. MustCompile is appropriate here because the pattern is a fixed program constant; use Compile and handle its error for configurable patterns. The distinction between absence and empty data must still be defined by the application. This expression is not a general configuration-file parser and provides no input-size limit.

See the Go standard-library reference.

Clean up

Remove the saved source and the empty scratch directory. Go manages its build cache separately. If the directory is not empty, inspect its contents before removing anything else.

rm -- go-regexp-optional-group-presence.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

Acknowledgements

This post was created with assistance from AI.

Last updated on