Go (RE2)

.env File Key-Value Line in GO

Parse KEY=value lines from .env config files, handling quoted values and trailing comments.

Try it in the GO tester →

Pattern

regexGO
^([A-Z_][A-Z0-9_]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^#\s]*))(?:\s*#.*)?$   (flags: m)

Go (RE2) code

goGo
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`(?m)^([A-Z_][A-Z0-9_]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^#\s]*))(?:\s*#.*)?$`)
	input := `DATABASE_URL=postgres://localhost/db`
	for _, match := range re.FindAllString(input, -1) {
		fmt.Println(match)
	}
}

Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.

How the pattern works

([A-Z_][A-Z0-9_]*) captures the variable name (uppercase + underscores by convention). The value alternation supports double-quoted, single-quoted, and unquoted values. (?:\s*#.*)? allows an optional inline comment. The m flag lets ^ and $ match individual lines in a multi-line file.

Examples

Input

DATABASE_URL=postgres://localhost/db

Matches

  • DATABASE_URL=postgres://localhost/db

Input

API_KEY="sk_live_abc123" # production

Matches

  • API_KEY="sk_live_abc123" # production

Input

lowercase=bad

No match

Same pattern, other engines

← Back to .env File Key-Value Line overview (all engines)