.env File Key-Value Line
Parse KEY=value lines from .env config files, handling quoted values and trailing comments.
Try it in RegexPro →Available in
JavaScript / ECMAScript code
const re = new RegExp("^([A-Z_][A-Z0-9_]*)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^#\\s]*))(?:\\s*#.*)?$", "m");
const input = "DATABASE_URL=postgres://localhost/db";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
Python (re) code
import re
pattern = re.compile(r"^([A-Z_][A-Z0-9_]*)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^#\\s]*))(?:\\s*#.*)?$", re.MULTILINE)
input_text = "DATABASE_URL=postgres://localhost/db"
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
Go (RE2) code
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.
Pattern
^([A-Z_][A-Z0-9_]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^#\s]*))(?:\s*#.*)?$ (flags: m)Raw source: ^([A-Z_][A-Z0-9_]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^#\s]*))(?:\s*#.*)?$
How it works
Examples
Input
DATABASE_URL=postgres://localhost/dbMatches
DATABASE_URL=postgres://localhost/db
Input
API_KEY="sk_live_abc123" # productionMatches
API_KEY="sk_live_abc123" # production
Input
lowercase=badNo match
—Common use cases
- •Linting and validating .env files in CI
- •Migrating dotenv configs between environments
- •Generating documentation from .env.example
- •Detecting committed secrets in PR diffs
Related patterns
Dockerfile ENV Instruction
File & PathMatch Dockerfile `ENV KEY=value` (or `ENV KEY value`) instructions, capturing key and value.
Hidden File (Dotfile)
File & PathMatches Unix-style hidden files (dotfiles) like .gitignore or .env.
Logfmt Key-Value Pair
LogsParse key=value pairs from logfmt-style log lines, supporting both quoted and unquoted values.
File Extension
File & PathCaptures the file extension from a filename.