.env File Key-Value Line in PY
Parse KEY=value lines from .env config files, handling quoted values and trailing comments.
Try it in the PY tester →Pattern
regexPY
^([A-Z_][A-Z0-9_]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^#\s]*))(?:\s*#.*)?$ (flags: m)Python (re) code
pyPython
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+.
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/dbMatches
DATABASE_URL=postgres://localhost/db
Input
API_KEY="sk_live_abc123" # productionMatches
API_KEY="sk_live_abc123" # production
Input
lowercase=badNo match
—