.*RegexQuick

Env Variable Regex

Regex for parsing environment variable files (.env format).

^([A-Z_][A-Z0-9_]*)=(.*)$
//
0 matches

About this pattern

This validates a line from a .env file: an upper-case key, then an equals sign, then everything remaining as the value. The key rules mirror shell conventions — upper case with underscores, and a first character that cannot be a digit, because POSIX shell identifiers cannot begin with one.

The value is captured with (.*), which accepts anything including nothing, so EMPTY= is valid and yields an empty string. That is deliberate: an explicitly empty value is meaningfully different from an absent variable, and conflating the two causes configuration bugs that are tedious to trace.

What the pattern does not handle is quoting, and .env files vary considerably. Values are sometimes wrapped in single or double quotes, sometimes contain escaped newlines, and sometimes span lines outright — a PEM-encoded private key being the usual offender. Different loaders also disagree about whether to expand ${VAR} references inside values. If you are writing a parser rather than a checker, test against your specific loader instead of assuming.

The part that matters most has nothing to do with the regex: .env files hold credentials and must never be committed. Add .env to .gitignore before the first commit, commit a .env.example carrying keys with placeholder values, and treat any secret that reaches a repository as compromised and in need of rotation — history is public even after deletion.

Worked examples

Keys must be upper-case and may not start with a digit, matching shell conventions.

Matches

  • API_KEY=secret
  • PORT=3000
  • EMPTY=

Does not match

  • lowercase=value
  • 1BAD=value

FAQ

Why must keys be upper case?

It mirrors POSIX shell conventions, where environment variables are upper case with underscores and cannot begin with a digit. Lower-case keys work in some loaders but break the convention consumers expect.

Is an empty value valid?

Yes — EMPTY= matches and yields an empty string. That is deliberately distinct from the variable being absent, a difference worth preserving in configuration.

Does this handle quoted or multi-line values?

No. Quoting rules, escaped newlines, and multi-line values such as PEM keys vary between loaders. Test against the specific loader you use rather than assuming.

What if I committed a .env file?

Treat every secret in it as compromised and rotate them. Deleting the file does not remove it from history. Add .env to .gitignore and commit a .env.example with placeholders instead.

More patterns