Environment Variable Secret Pattern (.env file) Regex for Python
/^((?:[A-Z_]+)?(?:PASSWORD|SECRET|TOKEN|KEY|CREDENTIAL|AUTH|API)[A-Z_]*)=([^\r\n#]{8,})$/mWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching environment variable secret pattern (.env file), ported and verified for Python. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your Python project — whether you're validating in a Django view, a FastAPI endpoint, or a standalone data processing script.
Python Implementation
# Environment Variable Secret Pattern (.env file)
# ReDoS-safe | RegexVault — Security > Secrets & Config
import re
environment_variable_secret_pattern_env_file_pattern = re.compile(r'^((?:[A-Z_]+)?(?:PASSWORD|SECRET|TOKEN|KEY|CREDENTIAL|AUTH|API)[A-Z_]*)=([^\r\n#]{8,})$')
def validate_environment_variable_secret_pattern_env_file(value: str) -> bool:
return bool(environment_variable_secret_pattern_env_file_pattern.fullmatch(value))
# Example
print(validate_environment_variable_secret_pattern_env_file("DATABASE_PASSWORD=mySecretPassword123")) # TrueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
DATABASE_PASSWORD=mySecretPassword123 | PORT=3000 |
STRIPE_SECRET_KEY=sk_live_4eC39HqLyjWD | NODE_ENV=production |
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG | # PASSWORD_COMMENT=ignored |
| — | SHORT=ab |
When to use this pattern
This pattern is drawn from the Security > Secrets & Config category and carries a ReDoS-safe certification. That matters for Python developers because particularly important in Python web servers where CPU-bound regex operations can stall concurrent request handling. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
Even if .env is in .gitignore, it may be committed before the .gitignore was added, or in a squashed commit. Use git log -- .env to check history. Consider pre-commit hooks that refuse to commit .env files.
Technical Notes
.env files should never be committed to version control. Use .gitignore to exclude .env files. The pattern uses multiline mode to match line-by-line. Capture group 1=key name, group 2=value. Value must be at least 8 chars to reduce false positives.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern